2012-03-19 71 views
2

我有以下情况。一个拥有照片列表集合和Photo对象的属性对象可以引用一个或多个属性对象。 所以我有这样的映射,我认为这是我的方案的精细流利Nhibernate拯救儿童实体

public PropertyMap() 
{ 
    Table("Property"); 
    Id(x => x.Id).GeneratedBy.Identity(); 
    Map(x => x.Title).Length(255).Not.Nullable(); 
    HasMany(x => x.Photos).KeyColumn("Id"); 
} 

public PhotoMap() 
{ 
    Table("Photo"); 
    Id(x => x.Id).GeneratedBy.Identity(); 
    Map(x => x.Version); 
    Map(x => x.ImageData).CustomSqlType("VARBINARY(MAX)").Length(160000); 
    Map(x => x.ImageMimeType); 
    References(x => x.Property) 
     .Column('PhotoId') 
     .Cascade.All(); 
} 

数据流 用户以某种形式进入数据和选择最多五个镜像每一个属性创建数据。 该数据发送到接收PropertyViewModel newData和IEnumerable图像的HttpPost控制器。如果modelstate没问题,我打开会话和事务,并将此数据发送到域模型,并将此数据保存到数据库。 一切正常,除了图像没有保存?没有错误抛出,在调试模式下图像通过regulary。

这里是代码创建控制器和内部PropertyViewModel ToDomainModel()方法

[HttpPost] 
public ActionResult Create(PropertyViewModel newData, IEnumerable<HttpPostedFileBase> images)   
{ 
    if (ModelState.IsValid) 
    { 
     using (/// open session) 
     { 
      using (// using transaction) 
      { 
      MyDomain.Property model = new MyDomain.Property(); 
      newData.ToDomainModel(model, images); 

      tx.Commit(); 
      session.Save(model); 
      } 
     } 
     return RedirectToAction("Index"); 
    } 
    else 
    { 
     return View(newData); 
    } 
} 

而且在内部视图模型ToDomainModel我一起接收图像和其他数据,并尝试将它们添加到收藏model.Photos并保存。

public void ToDomainModel(Property x, IEnumerable<HttpPostedFileBase> Images) 
    { 
     x.Id = Id;    

     List<Photo> Photos = new List<Photo>(); 
     foreach (var image in Images) 
     { 
      if (image != null && image.ContentLength > 0) 
      { 
       Photo p = new Photo(); 
       p.Property = x; 
       p.ImageMimeType = image.ContentType; 
       p.ImageData = new byte[image.ContentLength]; 
       image.InputStream.Read(p.ImageData, 0, image.ContentLength); 

       Photos.Add(p); 
      } 
     } 
     x.Photos = Photos; 

回答

4

您需要的Cascade.All()添加到您的HasMany映射PropertyMap,不要在PhotoMapReferences,因为要保存的Property实例,并需要级联其藏品也挽救其孩子。

+0

好的,现在我的房产地图有 HasMany(x => x.Photos).KeyColumn(“Id”)。Cascade.All(); 和PhotoMap有 引用(x => x.Property).Column(“PhotoId”); 现在保存我收到 无效的列名'PhotoId'。 – BobRock 2012-03-19 10:39:50

+0

@ user313378:你的'Photo'表中没有'PhotoId'列。您需要在'Photo'中指定引用父表'Property'的列。最有可能的是,这个列被称为'PropertyId'。 – 2012-03-19 10:42:39

+0

不错的工作人,谢谢你,爱stackoverflow。 – BobRock 2012-03-19 10:48:53