EF Core Entity Equality

c# entity-framework entity-framework-core

Question

Sorry if this is a dumb question, most of my experience with ORMs has not been EF, and looking this up online gets me a lot of bad hits. It's almost like "reference" means different things to different people...

If I write code like so:

using (var db = new DbContext())
{
    var entity1 = await db.Foos.FirstOrDefaultAsync(x => x.Id == 1);
    var entity2 = await db.Foos.FirstOrDefaultAsync(x => x.Id == 1);
    return entity1.Equals(entity2);
}

This returns true. Since my entity is a reference type, the Equals under the hood should be an Object.ReferenceEquals() call.

What I want to know is, is this reliable, i.e. will any entity represented by a particular database record in a context always be referentially equal, or can it "drop out" of the cache, get reloaded on demand and have a new reference like what happens in some less sophisticated ORMs? If an entity is loaded as part of a collection on another entity, is it still the same object? Are there rules/ settings that govern this behavior?

1
4
12/20/2017 4:12:22 PM

Accepted Answer

As @IvanStoev pointed out in the comments, the referential consistency is by design and a core part of EF, so the same object in the database should always reference the same object in the database context... at least in the scope of the specific database context you're in. YMMV if you are dealing with multiple database contexts.

2
3/6/2018 1:15:40 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow