1

I am looking for an automated way to iterate over all ObjectQueries and set the merge option to no tracking (read only context). Once i find out how to do it i will be able to generate a default read only context using a T4 template. Is this possible?

For example lets say i have these tables in my object context

SampleContext

  • TableA
  • TableB
  • TableC

I would have to go through and do the below.

SampleContext sc = new SampleContext();
sc.TableA.MergeOption = MergeOption.NoTracking;
sc.TableB.MergeOption = MergeOption.NoTracking;
sc.TableC.MergeOption = MergeOption.NoTracking;

I am trying to find a way to generalize this using object context.

I want to get it down to something like

foreach(var objectQuery : sc){
    objectQuery.MergeOption = MergeOption.NoTracking;
}

Preferably I would like to do it using the baseclass(ObjectContext):

ObjectContext baseClass = sc as ObjectContext
var objectQueries = sc.MetadataWorkspace.GetItem("Magic Object Query Option);

But i am not sure i can even get access to the queries. Any help would be appreciated.

Nix
  • 57,072
  • 29
  • 149
  • 198

2 Answers2

4

If you wanna do it for all ObjectSet, just one time, for all exection, try this:

var Ctx=YourDbContext;
var objSetProps = Ctx.GetType().GetProperties().Where(prop => prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(ObjectSet<>));
foreach(PropertyInfo objSetProp in objSetProps)
{
    ObjectQuery objSet = (ObjectQuery)objSetProp.GetValue(Ctx, BindingFlags.GetProperty, null, null, null);
    objSet.MergeOption=MergeOption.NoTracking;
}
Tiago GouvĂȘa
  • 15,036
  • 4
  • 75
  • 81
3

I think reflection will be the only choice for this. Something along the lines of:

IEnumerable<ObjectQuery> queries = from pd in context.GetType().GetProperties()
   where pd.PropertyType.IsSubclassOf(typeof(ObjectQuery))
   select (ObjectQuery)pd.GetValue(context, null);
Rookian
  • 19,841
  • 28
  • 110
  • 180
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273