![](/img/trans.png)
[英]How to implement optimistic concurrency on navigation properties in Entity Framework 6 Database First
[英]How do I return a Model from Entity Framework (Database First) that includes the Navigation Properties after the context is disposed?
實際上,我要問的內容比問題標題要寬得多……但這是一個特定的問題。
我正在嘗試精簡控制器,並將與Entity Framework的所有業務邏輯/交互都移入服務層,以使控制器根本不需要上下文,我認為這是做事的“正確”方法。
問題在於,當我創建一個返回域模型的服務層方法時,它不包含導航屬性,並且一旦我在控制器中調用此方法並需要訪問這些導航屬性,就已經處理了上下文。 然后,這迫使我對其他服務層方法進行多次調用,以獲取所需的其余屬性,以便可以創建視圖模型。
我確定問題是我沒有以正確的方式創建我的方法,或者缺少針對這種情況的正確體系結構的某些組件,因此這里有一些代碼來演示我在做什么。
服務層方法:
public IEnumerable<Paper> GetPapersForReview(int userID, string courseID, string role)
{
using (USGEntities context = new USGEntities())
{
IEnumerable<Paper> models = (from a in context.Papers
join b in context.Users_Roles on a.Paper_Types.Course_ID equals b.Course_ID
where a.Status == "REV" && a.Deleted == false && b.User_ID == userID && b.Role.Name == role && b.Course_ID == courseID
select a).ToList();
return models;
}
}
控制器方式:
public JsonResult GetPapersForReview(string courseID)
{
int user_id = new User().GetUserIDByDomainAccount(User.Identity.Name);
var vm = (from a in new PaperService().GetPapersForReview(user_id, courseID, "Reviewer")
select new PaperViewModel()
{
Paper_ID = a.ID,
Proposal_ID = a.Proposal_ID,
Expected_Start_Date = a.Expected_Start_Date
}).Distinct().ToList();
foreach (var paper in vm)
{
Proposal proposal = new ProposalService().GetProposal(paper.Proposal_ID);
Paper_Types paper_type = new PaperTypeService().GetPaperTypeByPaper(paper.Paper_ID);
paper.Paper_Type = paper_type.Description;
paper.Resources = new PaperService().GetResourceList(paper.Paper_ID);
paper.Proposal_Title = proposal.Title;
paper.Author = new UserService().GetNameByUserID(proposal.Author_User_ID);
}
return Json(vm, JsonRequestBehavior.AllowGet);
}
因此,您可以在調用Service Layer方法並獲得可以直接訪問的屬性后看到,然后我必須循環遍歷該過程,並進行其他調用以獲取我需要的其余屬性。 我知道這不是正確的做事方式。 那么,如何更好地構造事物以從服務層返回我需要的一切呢?
其他一些相關的問題是:我應該從服務層返回IEnumerables還是其他東西,是否需要在兩個地方都調用ToList()?
您具有.Include
擴展名:
public IEnumerable<Paper> GetPapersForReview(int userID, string courseID, string role)
{
using (USGEntities context = new USGEntities())
{
var result = context.Papers
.Include(paper => paper.User)
.Where(paper => paper.Status == "REV" && paper.Deleted == false && paper.User_ID == userID && paper.User.Role.Name == role && paper.Course_ID == courseID)
.ToList();
return result;
}
}
您甚至可以使用.ThenInclude
如果您具有多個級別):
.Include(p => p.Item)
.ThenInclude(p => p.SubItem)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.