之间有什么区别?
MyEntities.AsNoTracking()
和 context.MyEntities.MergeOption = MergeOption.NoTracking;
?
我从第二个推荐here中获取了合并选项,但我还没有真正找到它。我怀疑" MergeOption"从那时起,微软就删除了这件事。
答案 0 :(得分:2)
AsNoTracking只是MergeOption.NoTracking ObjectContext / ObjectSet版本(EF 4及以下版本)的DbContext / DbSet版本(EF 4.1及以上版本)。
AsNoTracking实施:
public static IQueryable AsNoTracking(this IQueryable source)
{
Check.NotNull(source, "source");
var asDbQuery = source as DbQuery;
return asDbQuery != null ? asDbQuery.AsNoTracking() : CommonAsNoTracking(source);
}
CommonAsNoTracking实施:
private static T CommonAsNoTracking<T>(T source) where T : class
{
DebugCheck.NotNull(source);
var asObjectQuery = source as ObjectQuery;
if (asObjectQuery != null)
{
return (T)DbHelpers.CreateNoTrackingQuery(asObjectQuery);
}
var noTrackingMethod = source.GetType().GetPublicInstanceMethod("AsNoTracking");
if (noTrackingMethod != null
&& typeof(T).IsAssignableFrom(noTrackingMethod.ReturnType))
{
return (T)noTrackingMethod.Invoke(source, null);
}
return source;
}
CreateNoTrackingQuery实现:
public static IQueryable CreateNoTrackingQuery(ObjectQuery query)
{
DebugCheck.NotNull(query);
var asIQueryable = (IQueryable)query;
var newQuery = (ObjectQuery)asIQueryable.Provider.CreateQuery(asIQueryable.Expression);
newQuery.ExecutionStrategy = query.ExecutionStrategy;
newQuery.MergeOption = MergeOption.NoTracking;
newQuery.Streaming = query.Streaming;
return newQuery;
}