0

Complex这是我对and的映射Dish

    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 模式——当来自前端的数据到来时,我创建所需的对象

在此处输入图像描述

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

4

1 回答 1

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

我会避免使用复杂的对象来管理 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 从复杂项目级联到菜肴是有意义的。

因此,我会确保您确实单独管理生命周期。希望这能将您推向正确的方向。

于 2013-04-07T14:09:50.510 回答