实体框架对象引用是否等于相同的数据库对象 [英] Do entity framework object references equal for same database objects

查看:51
本文介绍了实体框架对象引用是否等于相同的数据库对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我从不同的地方在逻辑上"(在数据库中)查询同一对象,那么实体框架是否会返回相同的对象引用.

Does entity framework return the same object reference if I query the "logically" (in database) same object from different places.

例如,我查询了名为Joe Black的客户(并假设现在我知道数据库中只有一个Joe Black.) Customer c = select ... blabla where ... Name == Joe Black...;和代码中的其他地方,我查询了Customer c2 = select... where.. ID==5,其中5是Joe Black的ID.我知道在数据库中它们映射到相同的对象,但是在代码级它们也映射到相同的对象吗?那么c1等于c2吗?我有要合并的列表,并检查对象的逻辑相等性(我现在无法访问数据库),我想知道Entity Framework对象是否可以很好地发挥作用,还是应该编写自定义比较器类.

For example, I queried customer with name Joe Black, (and assume for now I know that there's only one Joe Black in the database.) Customer c = select ... blabla where ... Name == Joe Black...; and in somewhere else in the code, I queried Customer c2 = select... where.. ID==5 where 5 is the ID of Joe Black. I know that in the database they map to the same object, but DO they also map to the same object in code level? So does c1 equal to c2? I have lists to merge and check for logical equality of the objects (I cannot access the database for now) and I was wondering whether Entity Framework objects will play nicely with it or should I write my custom comparer classes.

推荐答案

大多数ORM(包括实体框架和NHibernate)都使用此处为例.

Most ORMs, including Entity Framework and NHibernate, use the Identity Map Pattern to ensure there is only a single instance of a given entity per primary key. The identity map is scoped by the context, so two different contexts will create two objects which refer to the same entity. It is a good practice to have entities implement IEquatable, including overrides for equality operators so that '==' or '!=' will work. This is more involved than what one might think. Take a look here for an example.

这篇关于实体框架对象引用是否等于相同的数据库对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆