Monday, November 14, 2011 8:04 PM
I did a lot of googling but could not find an answer to this question. There is an easy way to get from DbContext down to ObjectContext but I cannot see a way of going from DbSet to ObjectSet and from there set the MergeOptions property.
Does anyone know how to do that?
Tuesday, November 15, 2011 8:58 AMModerator
Here is "AsNoTracking" method in DbContext:
using (var context = new UnicornsContext())
// Query for all unicorns without tracking them
var unicorns1 = context.Unicorns.AsNoTracking();
// Query for some unitcorns without tracking them
var unicorns2 = context.Unicorns
.Where(u => u.Name.EndsWith("ky"))
Have a nice day.
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- Marked As Answer by Valo Tuesday, November 15, 2011 1:46 PM
Tuesday, November 15, 2011 1:54 PMSweet! Thanks Alan!
Friday, May 18, 2012 12:28 PM
Alan, I think this probably achieves the end result that Valo was looking for, but I don't think it answers the question he was asking.
As I understand it, MergeOption.NoTracking applies to the query only, which means if you already have a DbSet (as described in Valo's original question), it's "too late" to apply that option if your intent was to improve performance by avoiding loading unnecessary data.
Since NoTracking is also often described as a solution for creating disconnected objects, if you're going straight to a DbSet (a good example would be the DbSet.Find method), it appears to me the only solution is to cast the DbContext to an IObjectContextAdapter and call Detach.
I came here to suggest that it would be nice if DbSet was also updated with the ability to specify an equivalent to NoTracking so that it became a characteristic of my instance of the data rather than a characteristic of how it was retrieved. However, as I write this I have realized that the Find method is really a query, and what we probably actually need is a way to specify NoTracking on convenience methods like Find. If there is a way to do this which I have overlooked, please let me know!