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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With