NHibernate Save Is Trying to Clear Child KeyColumn Id On Update

流过昼夜 提交于 2019-12-06 06:31:20

This is caused by the fact, that the Collection of children is not marked as inverse="true".

What you can do is: I. to remove the constraint from DB. NHiberante simply must (without the inverse setting) do 2 steps. Firstly update record to break relation, secondly (due to cascades) alse delete the item

II. Change the mapping, and entities. Like this:

A Child must have reference to the Parent:

public class Child
{
    public virtual Guid Id { get; set; }

    public virtual Guid ParentId { get; set; }
    public virtual Parent Parent { get; set; }
}

Mapping then will be like this:

public class ParentMap : ClassMap<Parent>
{
    public ParentMap()
    {
        Table("Parent");
        Id(x => x.Id);
        HasMany(x => x.Children)
            .KeyColumn("ParentId")
            .Cascade.SaveUpdate()
            .Not.LazyLoad()
            .Inverse() // here we do have the inverse setting
            ;
    }
}

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Table("Child");
        Id(x => x.Id);
        Map(x => x.ParentId).Not.Insert().Not.Update(); // this is readonly now
        References(x => x.Parent).Column("ParentId"); // just a Parent is writable
    }
}

Now, you have to all the time properly set the relation in the C# code. I.e. if child is added to Parents collection, it should also get set the Parent reference

parent.Children.Add(child);
child.Parent = parent;

NHibernate will now issue only one statement, to delete child from its table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!