LINQ to Entities reuse object instances?
Using LINQ to Entities sounds like a great way to query the database and get real CLR objects that I can modify, bind data, etc. But if I repeat the same query a second time, am I returning references to the same CLR objects, or a completely new set?
I don't want multiple queries to generate more and more copies of the same actual data. The problem here is that I can change the content of one object and save it back to the database, but another instance of the object still exists elsewhere and contains the old data.
source to share
In the same DataContext, you will get the same object if requested (DataContext maintains an internal cache for this).
Keep in mind that the objects you are working with are likely to change, so instead of one problem (data duplication), you might end up with another (concurrent access).
Depending on your business situation, it might be okay to allow a second stale transaction on commit.
Also imagine the old old IDataReader / DataSet script. The two queries will return two different reads that will populate different datasets. So the data duplication issue is not ORM specific.
source to share
[Oh; note that this answer applies to Linq-to-SQL, not Entity Framework.]
I left it here (rather than deleting it) because it is partially included in the theme and may be useful.
In addition to the other answers, note that the data context also has the ability to avoid doing a two-way run for simply "by primary key" queries - it checks the cache first.
Unfortunately this was completely broken in 3.5 and still half-broken in 3.5SP1, but it works for some requests. This can save you a lot of time if you receive individual items.
So, basically, IIRC you need to use:
// uses object identity cache (IIRC)
var obj = ctx.Single(x=>x.Id == id);
But not:
// causes round-trip (IIRC)
var obj = ctx.Where(x=>x.Id == id).Single();
source to share