为什么的ReferenceEquals和==操作符的行为,从不同的Equals不同、行为、操作、ReferenceEquals

由网友(滚开我有神经病 i)分享简介:我有一个实体,不覆盖任何平等成员\运营商。当比较他们两个代理服务器(我从 NHibernate的会议上得到了他们的)根据平等法的结果变化:的ReferenceEquals(一,二) - 假。 在第一==第二 - 假等于(一,二) - 真因为它们都存在于同一个会话的上下文并根据的 NHibernate的文档:.NH...

我有一个实体,不覆盖任何平等成员运营商。 当比较他们两个代理服务器(我从 NHibernate的会议上得到了他们的)根据平等法的结果变化:

的ReferenceEquals(一,二) - 假。 在第一==第二 - 假 等于(一,二) - 真

因为它们都存在于同一个会话的上下文并根据的 NHibernate的文档:

  

.NHibernate只能保证身份(一个== b时,缺省   实现的equals())单一的ISession里面!`

  

实例目前与某个持久化上下文有关联。它   拥有持久化标识(相当于主键值),或许,一   在数据库中相应的行。对于某一个特定的持久性   背景下,NHibernate的保证持久化标识等同   到CLR身份(对象在内存中的位置)。

那么,为什么不是所有的平等方法返回true?

更新: 我得到的enteties这种方式,查询会议ChildEntity并得到父母的实体使用LINQ的选择,与此类似:

  VAR童车= session.Query<儿童>();
变种父母= childs.Select(X => x.ParentEntity).ToList();
 

解决方案 JavaSE 重新学习 查漏补缺 5 Object类中的主要方法 instanceof操作符 对象的类型转换 操作符与equals方法的区别 直接输出对象输出的东西 再谈static关键字

在我得到童车的会议上,我把它们合并的会话。

  VAR童车= session.Query<儿童>();
//做一些东西
的foreach(VAR孩子在童车)
{
    session.Merge(子);
}

变种父母= childs.Select(X => x.ParentEntity).ToList();
 

这似乎合并脱离了会议实体,并返回连接到会话的新代理。

有可配

  VAR newChild对象=(儿童)session.Merge(子);
// 要么:
session.Update(子); //(我们有session.Clear()在我们的测试中,所以我不能用这个,因为它使在更新分离实体的烦恼
 

I have an Entity that doesn't override any of the equality membersoperators. When comparing two proxies of them (I got them from the Nhibernate session) the result changes according to the equality method:

ReferenceEquals(first, second) - false. first == second - false Equals(first, second) - true.

This is even more weird as they both exist in the same session context and according to the Nhibernate docs:

NHibernate only guarantees identity ( a == b , the default implementation of Equals()) inside a single ISession!`

And:

The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, NHibernate guarantees that persistent identity is equivalent to CLR identity (in-memory location of the object).

So why not all of the equality methods return true?

Update: I get the enteties this way, Query the session for ChildEntity and get the Parents Entities with Linq's select, similar to this:

var childs = session.Query<Child>();
var parents = childs.Select(x => x.ParentEntity).ToList(); 

解决方案

After I get childs from the session I Merge them with the session.

var childs = session.Query<Child>();
// Do some stuff
foreach (var child in childs)
{
    session.Merge(child);
}

var parents = childs.Select(x => x.ParentEntity).ToList(); 

It appear that the merge detached the entity from the session and return a new Proxy attached to the session.

It can be fixed with

var newChild = (Child)session.Merge(child);
// Or:
session.Update(child); // (We have session.Clear() in our tests so I can't use this because it makes troubles when you update detached Entity

阅读全文

相关推荐

最新文章