【问题标题】:How do I use eager loading with a repository pattern?如何在存储库模式中使用预加载?
【发布时间】:2016-06-30 14:34:39
【问题描述】:

我正在尝试清理我在应用程序中访问数据的方式。我已经开始转向存储库模式,我遇到的第一个问题是访问我的相关数据。

经过一些研究,我发现您可以使用 .Include() 来访问相关数据,但我似乎无法让它工作,我也不确定我的设置方式是否正确。

如何在存储库模式中使用预先加载?我已经包含了我的代码,以向您展示我如何设置的路线图。我省略了某些项目以保持简短。

IRepository.cs

public interface ICustomerRepository : IDisposable
{
    IEnumerable<customer> GetRelatedData();          
}

CustomerRepository.cs 在这里,我通过指定 .Include 然后定义相关表来添加预加载。

public IEnumerable<customer> GetRelatedData()
{
    return context.customers
        .Include(x => x.customer_cars)
        .ToList();
}

CustomerController.cs 我认为在这个级别上,GetRelatedData 将使用 CustomerRepository.cs 中定义的包含

public ActionResult Index()
{
    var customers = customersRepository.GetRelatedData();
    return View(customers);
}

索引视图 我现在需要显示数据,但由于我不确定如何在我的视图中显示相关数据,所以我被困在了这个阶段。

@model IEnumerable<Titan.Models.customer>
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.first_name)
        </th>    
    </tr>  
@foreach (var item in Model) {
<tr>

    <td>
        @Html.DisplayFor(modelItem => item.first_name)
    </td>       
</tr>
}

 </table>

可能是我的方法不正确。我从 ASP.NET MVC 教程中获得了指导,但我无法理解如何使这种急切加载场景在存储库模式中工作。任何帮助表示赞赏。

【问题讨论】:

  • 我已经重读了两次,但我仍然不确定你在问什么。您是在问如何获得子 customer_cars 对象?
  • 我真的在问两件事 a) 我的方法对于在存储库模式中使用预加载获取相关数据是否正确? b) 如果是这样,我如何将“customers_car”对象放入我的视图中,以便我可以显示这些相关数据?
  • 请发布您的“客户”类的代码

标签: c# asp.net-mvc repository-pattern eager-loading


【解决方案1】:

您应该在客户对象中收集客户汽车。

类似这样的:

@foreach (var item in Model) {
<tr>
   @foreach(var car in item.customer_cars){
  <td>
     @Html.DisplayFor(car => car.model)
  </td>       
 }
</tr>
}

【讨论】:

    猜你喜欢
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    相关资源
    最近更新 更多