[英]NHibernate not deleting orphans on update
I have a class, which has a list of an abstract class: 我有一个类,其中包含一个抽象类的列表:
public class Foo
{
public int Id { get; set; }
public IList<Bar> Bars { get; set; }
}
public abstract class Bar
{
public int Id { get; set; }
}
I have mapped the Bars as such: 我已经绘制了这样的酒吧:
HasMany(f => f.Bars).Cascade.AllDeleteOrphans();
However when I update a Foo
to remove a Bar
it doesn't delete the orphan but it does set Bar's Foo_id
column to NULL
? 但是,当我更新Foo
以删除Bar
它不会删除孤立对象,但会将Bar的Foo_id
列设置为NULL
?
I read around and saw answers saying to inverse the HasMany
so I tried: 我四处阅读,看到答案说要逆转HasMany
所以我尝试了:
HasMany(f => f.Bars)
.Inverse()
.Cascade.AllDeleteOrphans();
But then when saving the Bar
always had NULL
as the Foo_id
. 但是然后在保存Bar
时,其Foo_id
始终为NULL
。 This was also the case when I tried adding a KeyColumn
: 当我尝试添加KeyColumn
时也是如此:
HasMany(f => f.Bars)
.Inverse()
.KeyColumn("Foo_id")
.Cascade.AllDeleteOrphans();
Using these mappings: 使用这些映射:
public class FooMap : ClassMap<Foo>
{
public FooMap ()
{
Id(x => x.Id);
HasMany(f => f.Bars).Inverse().Cascade.AllDeleteOrphans();
}
}
public class BarMap : ClassMap<Bar>
{
public BarMap ()
{
Id(x => x.Id);
References(x => x.Foo);
}
}
To remove, you need to disassociate the bar from the foo from both ways: 要删除,您需要通过两种方式将bar与foo解除关联:
// get foo object
var foo = dao.GetFooByID(1);
var barToRemove = foo.Bars[0]; // find the first bar
// disassociate the objects to properly trigger cascade deletion
barToRemove.Foo = null;
foo.Bars.Remove(barToRemove);
dao.SaveFoo(foo);
On the other hand, to add, you need to associate the objects from both ways as well: 另一方面,要添加,还需要同时通过两种方式关联对象:
// get foo object
var foo = dao.GetFooByID(1);
var barToAdd = new Bar(); // new bar to add
// associate the objects to properly trigger cascade save
barToAdd.Foo = foo;
foo.Bars.Add(barToAdd);
dao.SaveFoo(foo);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.