![](/img/trans.png)
[英]Cannot access a disposed object. Object name: 'DataContext accessed after Dispose
[英]LINQ to SQL -> Cannot access a disposed object. Object name: 'DataContext accessed after Dispose
假設我有兩張桌子,即學生和學校。 在我的學生表中,我有一個fkSchoolId鏈接到學校記錄。 但是,如果我檢索我的記錄如下
public static List<Student> GetByType(string connString, int type)
{
using (mydb_DataContext db = new mydb_dbDataContext(connString))
{
return (from t1 in db.Students
where t1.type = type
select t1).ToList();
}
}
我將有一個Student對象列表,我可以在foreach循環中訪問它。 但是當我這樣做時,我會在檢索學校名稱時收到錯誤。
foreach(Student student in DAL.StudentLogic.GetByType(5))
{
string schoolName = student.School.Name;
}
System.ObjectDisposedException:'無法訪問已處置的對象。 對象名:'Dispose后訪問的DataContext。'。'
我是否可以知道如何將外部信息存儲在返回對象中以便我可以訪問它們? 或者更好的方法,如果我可以指定只加載學校名稱?
更新:如果我這樣做,它可以工作,但不確定它將對性能產生多大影響。 我將在下周再次對該主題進行基准測試和更新。
public static List<Student> GetByType(string connString, int type)
{
using (mydb_DataContext db = new mydb_dbDataContext(connString))
{
List<Student> students = (from t1 in db.Students where t1.type = type select t1).ToList();
foreach(Student student in students)
{
student.School.Name = db.Schools.Where(q => q.SchoolId == student.fkSchoolId).FirstOrDefault().Name;
}
}
}
我將能夠訪問返回對象中的student.School.Name。
將DeferredLoadingEnabled
屬性設置為false
:
獲取或設置一個值,該值指示是否延遲加載一對多關系或一對一關系。
因此,在實現查詢時將檢索相關數據,而不是在稍后階段(在上下文處理之后)檢索相關數據
public static List<Student> GetByType(string connString, int type)
{
using (mydb_DataContext db = new mydb_dbDataContext(connString))
{
db.DeferredLoadingEnabled = false;
return (from t1 in db.Students
where t1.type = type
select t1).ToList();
}
}
然而,考慮思考(取決於整體設計/程序要求和負載)使該上下文在該類的生命周期中保持打開(這看起來像一個DAL類)。 然后實現IDisposable
接口並在其中處理上下文。 (請記住,必須明確調用Dispose
)。
如果你想要的只是學校名稱並且你使用的是C#7.0,你可以這樣使用命名的元組 :
public static List<(Student Student, string SchoolName)> GetByType(string connString, int type)
{
using (mydb_DataContext db = new mydb_dbDataContext(connString))
{
return (from t1 in db.Students
join school in db.Schoold on t1.SchoolId equals school.Id
where t1.type = type
select (t1, school.Name)).ToList();
}
}
如果出現編譯錯誤CS8137,則需要安裝System.ValueTuple
的Nuget包
使用Linq2Sql,您可以使用LoadWith ,例如
using (mydb_DataContext db = new mydb_dbDataContext(connString))
{
DataLoadOptions op = new DataLoadOptions();
op.LoadWith<Student>(o => o.School);
db.LoadOptions = op;
return (from t1 in db.Students
where t1.type = type
select t1).ToList();
}
一個缺點是這是檢索學校表中的所有列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.