开发者

Way to automate setting of MergeOptions

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 Objec开发者_C百科tContext
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.


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;
}


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜