我在MVC3應用程序中看到了很多使用實體框架的例子,它們都是非常簡單的演示程序,其中只有一個帶有edmx的mvc3 web項目。如何在使用Entity Framework的多層應用程序中正確管理ObjectContext生命週期?
因此,他們可以通過「使用」語句中使用的打開和關閉連接的最佳做法:
using(var context = new SchoolEntities())
{
// do some query and return View with result.
}
而且,它可以正確地使用延遲加載(導航屬性)中的「使用」語句內的,因爲上下文尚未 配置:
foreach(var item in student.Course)
{
// do something with the navigation property Course
}
所有的事情似乎是完美的,直到它變成一個n層應用程序。
我創建了DAL,BLL和一個MVC3 UI。
的DAL裏面有EDMX,和運營商類,如SchoolDA.cs:
public class StudentDA()
{
public Student FindStudent(int studentId)
{
using(var context = new SchoolContext())
{
// do query, return a student object.
}
}
}
然後,在BLL,如果我使用:
var student = studentDa.FindStudent(103);
然後調用它的導航屬性:
student.Course
我會得到(當然)的錯誤:
的ObjectContext的實例已經設置,不能再用於需要連接的操作。
所以,我必須要改變StudentDA.cs這樣的:
public Student FindStudent(int id)
{
using(var studentDa = new StudentDA())
{
// this can access navigation properties without error, and close the connection correctly.
return studentDa.FindStudent(id);
}
}
所有的事情似乎是完美的再次直到滿足:
public class StudentDA() : IDisposable
{
private SchoolEntites context;
public StudentDA()
{
context = new SchoolEntities();
}
public void Dispose()
{
context.Dispose();
}
public Student FindStudent(int studentId)
{
// do query, return a student object.
}
}
然後,BLL會喜歡這種改變Update()方法。
現在,如果我想更新是從BLL.FindStudent(),採取context.SaveChanges()將返回0學生對象,因爲上下文已經設置在BLL.FindStudent(),並沒有什麼會更新到數據庫。
var optStudent = new StudentBO();
var student = optStudent.FindStudent(103);
student.Name = "NewValue";
optStudent.Update(student);
有沒有人有關於如何在3輪胎應用中使用EntityFramework的想法?或者我如何正確管理上下文。我將在Web層中經常使用導航屬性,但我不能始終保持連接打開以消耗服務器內存。
搜索_Inversion of Control_和_Dependency Injection_ – Eranga 2012-08-14 04:26:08
@Eranga還確保您保持上下文範圍有限,.InRequestScope或.InTransientScope wit h ninject,這樣可以防止串擾並附加問題 – 2012-08-14 04:34:45