Update: This does not actually work. See Comments!
I hate it when I search on StackOverflow, and the answer is: “You can't!” or "You could, but only if you completely change every call you ever made."
Repel someone? I was hoping this would be a DbContext installation. But since it is not, I made one using reflection.
This convenient method will set AsNoTracking for all properties of type DbSet.
private void GloballySetAsNoTracking() { var dbSetProperties = GetType().GetProperties(); foreach (PropertyInfo pi in dbSetProperties) { var obj = pi.GetValue(this, null); if (obj.GetType().IsGenericType && obj.GetType().GetGenericTypeDefinition() == typeof(DbSet<>)) { var mi = obj.GetType().GetMethod("AsNoTracking"); mi.Invoke(obj, null); } } }
Add it to the overloaded DbContext constructor.
public ActivationDbContext(bool proxyCreationEnabled, bool lazyLoadingEnabled = true, bool asNoTracking = true) { Configuration.ProxyCreationEnabled = proxyCreationEnabled; Configuration.LazyLoadingEnabled = lazyLoadingEnabled; if (asNoTracking) GloballySetAsNoTracking(); }
It uses reflection, which means that someone will quickly comment that this is a performance hit. But is this really a big hit? Depends on your use case.
Rhyous Nov 25 '15 at 21:05 2015-11-25 21:05
source share