Nhibernate不保存hasManyToMany数据

时间:2013-04-06 18:57:59

标签: c#-4.0 nhibernate fluent-nhibernate

以下是我ComplexDish

的映射
    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

对象保存但不是整个对象只有名称和描述已保存,但产品集合不保存。我想我忘记了一些简单的事情,请帮助我。

1 个答案:

答案 0 :(得分: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);

我会避免复杂的Object管理Dish对象的生命周期,如

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);

此外,由于菜肴肯定会在两个复杂的对象之间共享,因此将DELETE从复杂项目级联到菜肴是有意义的。

因此,我会确保您分别管理生命周期。 希望这会把你推向正确的方向。