2013-04-06 45 views
0

這裏是我的映射ComplexDishNHibernate的不保存hasManyToMany數據

public class ComplexMapping:ClassMap<Complex> 
    { 
     public ComplexMapping() 
     { 
      Table("ComplexTable"); 

      Id(comp => comp.Id,"ComplexId").GeneratedBy.Identity(); 
      Map(comp => comp.Name,"Name").Not.Nullable(); 
      Map(comp => comp.Subscribe, "DescriptionComplex"); 

      HasManyToMany(comp => comp.ScrollOfDish) 
       .Table("ComplexDish") 
       .ParentKeyColumn("ComplexId") 
       .ChildKeyColumn("DishId").Cascade.All(); 

     } 
    } 

    public class DishMapping:ClassMap<Dish> 
    { 
     public DishMapping() 
     { 
      Table("DishTable"); 

      Id(dish => dish.Id, "DishId").GeneratedBy.Identity(); 

      Map(dish => dish.Name); 
      Map(dish => dish.Description); 
      Map(dish => dish.Price); 

      References(x => x.Category, "CategoryId").Cascade.None(); 

      HasManyToMany(comp => comp.Scroll) 
       .Table("ComplexDish") 
       .ParentKeyColumn("DishId") 
       .ChildKeyColumn("ComplexId").Inverse(); 

     } 
    } 

我使用DAO模式 - 當從前端數據來創建需要的對象

enter image description here

和對象保存但不是整個對象只有名稱和描述已保存,但收集產品不保存。我想我忘了一些簡單的事情,請幫助我。

回答

0

通常對我而言,多對多表示實體本身管理其生命週期的兩個獨立實體之間的關聯。

例如。在您的情況

var firstDish = new Dish(); 
var secondDish = new Dish(); 

// 01 -- both dish objects are now attached to the session 
session.SaveOrUpdate(firstDish); 
session.SaveOrUpdate(secondDish); 


var firstComplexObject = new Complex(); 
firstComplexObject.ScrollOfDish.Add(firstDish); 
firstComplexObject.ScrollOfDish.Add(secondDish); 

// 02 -- first Complex Object now attached to the session 
session.SaveOrUpdate(firstComplextObject); 

var secondComplexObject = new Complex(); 
secondComplexObject.ScrollOfDish.Add(firstDish); 
secondComplexObject.ScrollOfDish.Add(secondDish); 

// 03 -- second Complex Object now attached to the session 
session.SaveOrUpdate(secondComplextObject); 

我會避免複雜的對象管理菜對象的生命週期一樣

var firstDish = new Dish(); 
var secondDish = new Dish(); 

var firstComplexObject = new Complex(); 
firstComplexObject.ScrollOfDish.Add(firstDish); 
firstComplexObject.ScrollOfDish.Add(secondDish); 


// the dish object are not attached to session 
// hence the NHibernate has to save the entire object graph here!!!! 
// 01 -- first Complex Object now attached to the session 
session.SaveOrUpdate(firstComplextObject); 

var secondComplexObject = new Complex(); 
secondComplexObject.ScrollOfDish.Add(firstDish); 
secondComplexObject.ScrollOfDish.Add(secondDish); 

// 02 -- second Complex Object now attached to the session 
session.SaveOrUpdate(secondComplextObject); 

此外,由於菜肯定會兩個複雜對象之間共享,這將使意義不級聯從複雜項目刪除到菜。

因此,我會確保您分開管理生命週期。 希望這會把你推向正確的方向。

+0

非常感謝。問題出在這方面,我已經用你的幫助解決了它) – 2013-04-08 05:02:45