tags:

views:

435

answers:

3

Using LINQ to Entities sounds like a great way to query against a database and get actual CLR objects that I can modify, data bind against and so forth. But if I perform the same query a second time do I get back references to the same CLR objects or an entirely new set?

I do not want multiple queries to generate an ever growing number of copies of the same actual data. The problem here is that I could alter the contents of one entity and save it back to the database but another instance of the entity is still in existence elsewhere and holding the old data.

+1  A: 

Within the same DataContext, my understanding is that you'll always get the same objects - for queries which return full objects instead of projections.

Different DataContexts will fetch different objects, however - so there's a risk of seeing stale data there, yes.

Jon Skeet
+1  A: 

In the same DataContext you would get the same object if it's queried (DataContext maintains internal cache for this).

Be aware that that the objects you deal are most likely mutable, so instead of one problem (data duplication) you can get another (concurrent access).

Depending on business case it may be ok to let the second transaction with stale data to fail on commit.

Also, imagine a good old IDataReader/DataSet scenario. Two queries would return two different readers that would fill different datasets. So the data duplication problem isn't ORM specific.

A: 

[oops; note that this reply applies to Linq-to-SQL, not Entity Framework.]

I've left it here (rather than delete) because it is partly on-topic, and might be useful.


Further to the other replies, note that the data-context also has the ability to avoid doing a round-trip for simply "by primary key" queries - it will check the cache first.

Unfortunately, it was completely broken in 3.5, and is still half-broken in 3.5SP1, but it works for some queries. This can save a lot of time if you are getting individual objects.

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();
Marc Gravell