Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do entity framework object references equal for same database objects

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

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.

like image 947
Can Poyrazoğlu Avatar asked Jul 01 '11 01:07

Can Poyrazoğlu


1 Answers

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.

like image 144
eulerfx Avatar answered Oct 23 '22 22:10

eulerfx