我正在使用Linq进行SQL,为了进行优化,我想将DataContext.ObjectTrackingEnabled设置为false,以用于不需要更改或添加对象的查询。在我的应用程序中,我已经使用了一个DataContext,所以为了将ObjectTrackingEnabled设置为false,我需要创建一个新的DataContext。所以我想做这样的事情:
public static MyObj GetMyObj(long id)
{
using (MyDataContext dc = new MyDataDataContext("connectionstring"))
{
dc.ObjectTrackingEnabled = false;
return dc.MyObjs.FirstOrDefault(x => x.ID == id);
}
}
但是我返回的MyObj似乎“被处置了一半”,因为当我尝试访问它的成员时,它们全都为空。像这样:
var myObj = GetMyObj(10);
var test = myObj.MyMember.Count(); // MyMember is now null, but shouldn't be
但是,如果我不使用它,那么我会得到正确的Count():
public static MyObj GetMyObj(long id)
{
var dc = DCManager.Get("myDataContext") // gets the normal DC that's used throughout the application
return dc.MyObjs.FirstOrDefault(x => x.ID == id);
}
var myObj = GetMyObj(10);
var test = myObj.MyMember.Count(); // MyMember is now not null and its Count() is not 0
有没有一种方法可以使用ObjectTrackingEnabled = false而不丢失返回值上的数据,或者只能在返回值类型时使用此“模式”?我想我需要在返回后强制对要使用的成员对象进行快速加载,因此我尝试添加DataLoadOptions.LoadWith,但仍无法获取基础对象:
public static MyObj GetMyObj(long id)
{
using (MyDataContext dc = new MyDataDataContext("connectionstring"))
{
dc.ObjectTrackingEnabled = false;
DataLoadOptions load = new DataLoadOptions();
load.LoadWith<MyObj>(d => d.MyMember);
return dc.MyObjs.FirstOrDefault(x => x.ID == id);
}
}
var myObj = GetMyObj(10);
var test = myObj.MyMember.Count(); // MyMember is null which it shouldn't be
答案 0 :(得分:0)
您与最新更新非常接近。没错,这是关于延迟/渴望加载的。但是您没有将该特定上下文对象告诉您已配置的use the options:
public static MyObj GetMyObj(long id)
{
using (MyDataContext dc = new MyDataDataContext("connectionstring"))
{
dc.ObjectTrackingEnabled = false;
DataLoadOptions load = new DataLoadOptions();
load.LoadWith<MyObj>(d => d.MyMember);
dc.LoadOptions = load; //<-- New line
return dc.MyObjs.FirstOrDefault(x => x.ID == id);
}
}
var myObj = GetMyObj(10);
var test = myObj.MyMember.Count(); // MyMember is null which it shouldn't be
(作为一种选择,我也将load
重命名为options
,因为我认为这样可以更好地描述该对象是什么)