gpt4 book ai didi

c# - 在处理上下文后,如何从包含导航属性的 Entity Framework (数据库优先)返回模型?

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:16 25 4
gpt4 key购买 nike

我要问的实际上比问题标题要宽泛一点……但这是一个特定的问题。

我正在尝试精简我的 Controller 并将所有业务逻辑/与 Entity Framework 的交互移动到服务层中,以便我的 Controller 根本不需要上下文,我认为这是做事的“正确”方式.

问题是,当我创建一个返回域模型的服务层方法时,它不包含导航属性,一旦我在我的 Controller 中调用此方法并需要访问这些导航属性,上下文已经处置。然后,这迫使我多次调用其他服务层方法来获取我需要的其余属性,以便我可以创建我的 View 模型。

我确定问题是我没有以正确的方式创建我的方法,或者缺少适合这种情况的正确架构的某些组件,所以这里有一些代码来演示我在做什么。

服务层方法:

        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;
}
}

Controller 方法:

        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);
}

因此您可以看到,在我调用服务层方法并获取我可以直接访问的属性之后,我必须循环返回并进行额外的调用以获取我需要的其余属性.我知道这不是做事的正确方法。那么我该如何更好地构建事物以从服务层返回我需要的一切?

其他一些相关问题是:我应该从服务层返回 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)

关于c# - 在处理上下文后,如何从包含导航属性的 Entity Framework (数据库优先)返回模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43233750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com