有人可以向我解释一下关于 NHibernate 如何处理复合元素的这个小谜团吗?
我的课程看起来像这样;
public class Blog
{
public virtual int Id
{
get;
private set;
}
public virtual ISet<Comment> Comments
{
get;
set;
}
}
public class Comment
{
public virtual string CommentText
{
get;
set;
}
public virtual DateTime Date
{
get;
set;
}
}
和这样的映射;
<class name="Blog" table="blog">
<id name="Id" column="id" unsaved-value="0">
<generator class="hilo"/>
</id>
<set name="Comments" table="blog_comments">
<key column="blog_id" />
<composite-element class="Comment">
<property name="CommentText" column="comment" not-null="true" />
<property name="Date" column="date" not-null="true" />
</composite-element>
</set>
</class>
但是,当我执行这样的选择时;
using (ITransaction transaction = session.BeginTransaction())
{
Blog blog = session.CreateCriteria(typeof(Blog))
.SetFetchMode("Comments", FetchMode.Eager)
.Add(Expression.IdEq(2345))
.UniqueResult();
transaction.Commit();
}
NHibernate 发出一个带有连接的选择来获取包含帖子的博客,但然后删除所有评论,然后插入评论!它为什么要这样做?如果我不使用事务,那么它将只执行选择,而不是像我期望的那样执行删除和插入。我缺少什么?我正在使用 NHibernate 2.0
我认为你需要重写 Comment 上的 Equals() 和 GetHashCode() 。 NHibernate 没有用于实体相等的 ID,因此您必须定义什么使评论实体等于另一个评论。
可能是错的:)
Edit
From nhibernate.info https://nhibernate.info/doc/nhibernate-reference/components.html#components-incollections (8.2)
注意:如果定义一组复合元素,正确实现 Equals() 和 GetHashCode() 非常重要。
以及实现 Equals / GetHashCode 的示例nhibernate.info https://nhibernate.info/doc/nhibernate-reference/persistent-classes.html#persistent-classes-equalshashcode (4.3)
public class Cat
{
...
public override bool Equals(object other)
{
if (this == other) return true;
Cat cat = other as Cat;
if (cat == null) return false; // null or not a cat
if (Name != cat.Name) return false;
if (!Birthday.Equals(cat.Birthday)) return false;
return true;
}
public override int GetHashCode()
{
unchecked
{
int result;
result = Name.GetHashCode();
result = 29 * result + Birthday.GetHashCode();
return result;
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)