CRM Development

Solutionist has designed the architecture for a new CRM system for use in the medical imaging industry.

Thursday 8 September 2011

Entity Framework Tip #1 - Using MergeOption to get latest entities

Hopefully this is the first of various Entity Framework tips that I've gleaned along the way.
They'll serve as reminders for me and if they can help other people, they will have served their purpose.

Ok, what's wrong with this?

(We're using STEs because we're throwing things across the network). 
I was doing some testing and had code that looked like this.

 DBEntities context1 = new DBEntities();
 DBEntities context2 = new DBEntities();
 Site newSite = new Site();
 newSite.SiteName = "QAZ";
 context1.ApplyChanges("Sites", newSite);
 Site site2 = context2.Sites.Where(s => s.ID == newSite.ID).FirstOrDefault();
 // update the site...
 site2.ChangeTracker.ChangeTrackingEnabled = true; // Because they're STEs
 site2.SiteName = "QAZ QAZ";
 context2.ApplyChanges("Sites", site2);
 // I thought I'd use the first context to query for the updated site...
 var query = context1.Sites.Where(s => s.ID == newSite.ID);
 Site site3 = query.FirstOrDefault();

What's the SiteName of site3?

No, it's not "QAZ QAZ" - it's "QAZ"

Why is that? 

Because the site already exists in context1 - so even though a database query is actually executed, EF will not overwrite what's in context1 because its cache already contains an entity with that EntityKey.

How to make sure that I actually get the latest values back?

Set the MergeOption on the objectSet before doing the call - as follows...
context1.Sites.MergeOption = MergeOption.OverwriteChanges;

The default option is AppendOnly which won't update the context if it finds an entity with the
same entityKey present.

Another tip from the twighlight world of entity framework...

One thing I've yet to investigate is how delayed execution would affect MergOption settings.
So, if I reset the MergeOption after the query to AppendOnly and then do further queries before finally executing the query - would the different MergeOptions be applied at the right time... hmmm...