C# NHibernate正在删除子集合对象StaleObjectStateException
我遇到了NHibernate的问题,我不能很好地找到最好的解决方案。 我有一个带有子集合的Customer类,我正试图通过从列表中删除该集合中的项目来删除该项目 类和映射如下所示:C# NHibernate正在删除子集合对象StaleObjectStateException,c#,nhibernate,C#,Nhibernate,我遇到了NHibernate的问题,我不能很好地找到最好的解决方案。 我有一个带有子集合的Customer类,我正试图通过从列表中删除该集合中的项目来删除该项目 类和映射如下所示: public class Customer : Entity<Customer> { public virtual IList<WishlistProduct> Wishlist { get; set; } public Customer() { Wi
public class Customer : Entity<Customer>
{
public virtual IList<WishlistProduct> Wishlist { get; set; }
public Customer()
{
Wishlist = new List<WishlistProduct>();
}
public virtual bool RemoveFromWishlist(int id)
{
bool removed = false;
for (int x = Wishlist.Count - 1; x >= 0; x--)
{
if (Wishlist[x].Product.Id == id)
{
Wishlist[x].Customer = null;
Wishlist.RemoveAt(x);
removed = true;
}
}
return removed;
}
}
我正在使用以下会话管理技术:
builder.Register(x => MyApplication.SessionFactory.OpenSession()).As<ISession>()
.InstancePerHttpRequest()
.OnRelease(x =>
{
x.Flush();
x.Close();
});
builder.Register(x=>MyApplication.SessionFactory.OpenSession()).As()
.InstancePerHttpRequest()实例
.OnRelease(x=>
{
x、 冲洗();
x、 Close();
});
我可以从SQL日志中看到,这确实生成了正确的DELETE语句来删除记录,但是在OnRelease回调中,我得到了一个StaleObjectStateException:“行被另一个事务更新或删除(或者未保存的值映射不正确)”。在异常详细信息中,我可以看到它正在删除的子对象上运行
为什么会发生这种情况?在调用Flush之前,我看不到子对象是如何被修改的。除了从列表中删除子对象之外,我不会对父对象或子对象执行任何操作
我知道我可以单独删除子对象,但业务逻辑似乎更自然,能够从父对象列表中删除子对象并处理删除
非常感谢您提供的任何帮助或见解。您需要通过从集合中删除项目并将对其父项的引用置为空来维护双方的关系
public virtual bool RemoveFromWishlist(int id)
{
bool removed = false;
for (int x = Wishlist.Count - 1; x >= 0; x--)
{
if (Wishlist[x].Product.Id == id)
{
Wishlist[x].Customer = null;
Wishlist.RemoveAt(x);
removed = true;
}
}
return removed;
}
除了@jamie ide答案 在那种情况下你用错了。您需要使用AllDeleteOrphan():
内部类CustomerMapping:EntityMapping
{
内部CustomerMapping()
{
HasMany(x=>x.Wishlist)
.Inverse()
.Cascade.AllDeleteOrphan();
}
}
根据您的建议进行了更新,取消了家长参考,没有任何影响,我很抱歉。同样的例外。我可能不理解你的域模型,你也有一个产品类。根据我的经验,出现错误的根本原因是从仍具有非空外键集的集合中删除的项。因此,仅从父集合中删除子对象是无法删除的吗?我正在取消FK父引用。。。是否需要使用WishlistRepository单独删除对象?将级联更改为AllDeleteOrphan,出现相同错误。我也面临相同问题,但在更改.hbm文件中的级联后,问题得到解决。请提供主表和子表的.hbm结构。谢谢,Bhushan BabrasI我没有使用XML映射,我使用的是流畅的映射。你对瀑布做了什么改变?
builder.Register(x => MyApplication.SessionFactory.OpenSession()).As<ISession>()
.InstancePerHttpRequest()
.OnRelease(x =>
{
x.Flush();
x.Close();
});
public virtual bool RemoveFromWishlist(int id)
{
bool removed = false;
for (int x = Wishlist.Count - 1; x >= 0; x--)
{
if (Wishlist[x].Product.Id == id)
{
Wishlist[x].Customer = null;
Wishlist.RemoveAt(x);
removed = true;
}
}
return removed;
}
internal class CustomerMapping : EntityMapping<Customer>
{
internal CustomerMapping()
{
HasMany(x => x.Wishlist)
.Inverse()
.Cascade.AllDeleteOrphan();
}
}