如何使用Entity Framework和Repository Pattern加载相关实体 [英] How to load the related entities using Entity Framework and the Repository Pattern

查看:123
本文介绍了如何使用Entity Framework和Repository Pattern加载相关实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与


  1. 我决定更改Generic Repository模式,并为每个实体使用特定的存储库。然而,我只是不能找到如何使其工作,因为在我的HTML中,我需要显示相关实体的一些字段。

  1. I have decided to change the Generic Repository pattern and used a specific repository for each entity. However I just cant find how to make it work because in my html I need to show some fields from related entities.

最好用Iqueryable替换Ienumerable ?

Is it better to replace Ienumerable with Iqueryable?

资源库界面

 public interface IApplicantPositionRepository : IDisposable
    {
        IEnumerable<ApplicationPositionHistory> GetApplicationPositionHistories(int applicantId, int positionId);
                   void Save();
    }

存储库界面实现。

public IEnumerable<ApplicationPositionHistory> GetApplicationPositionHistories(int applicantId, int positionId)
        {
            return context.ApplicationsPositionHistory.Where(d => d.applicantPosition.ApplicantID == applicantId && d.applicantPosition.PositionID == positionId);
        }

控制器方法

public ViewResult History(int applicantId, int positionId)
        {
            var history=applicantPositionRepository.GetApplicationPositionHistories(applicantId, positionId);
            return View(history);
        }

Html。

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.applicantPosition.Applicant.name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.applicantPosition.Position.name)
        </td>


推荐答案

我个人喜欢IList&T但是这是个人选择当然

Personally I like IList<T> but thats a personal choice of course

要包括一个相关的表,只需简单地(这个不使用相关类名称的字符串的语法,如.Include(RelatedEntityName)我认为是如果我记得正确,请在4.1中添加:

To include a related table simply do (this syntax of not using a string for RelatedEntityName like .Include("RelatedEntityName") I think was added in 4.1 if I recall correctly:


 return context.ApplicationsPositionHistory.Where(d => d.applicantPosition.ApplicantID == applicantId && d.applicantPosition.PositionID == positionId).Include(o=>o.RelatedEntityName);

不要从存储库返回IQueryable,

Never return IQueryable from a repository. It's not easily testable since this is very provider specific.

如果呼叫者不需要额外的详细信息,我也会创建单独的方法

I would also create separate methods if the caller does not require additional details either.

这篇关于如何使用Entity Framework和Repository Pattern加载相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆