我正在尝试清理我在应用程序中访问数据的方式。我已经开始转向存储库模式,我遇到的第一个问题是访问我的相关数据。
经过一些研究,我发现您可以使用 .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);
}
索引 View 我现在需要显示数据,但我被困在这个阶段,因为我不确定如何在我的 View 中显示相关数据。
@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 教程中获取了指导,但我无法理解如何使这种预加载方案在存储库模式中工作。感谢您的帮助。
最佳答案
您应该在客户对象中包含客户汽车集合。
像这样:
@foreach (var item in Model) {
<tr>
@foreach(var car in item.customer_cars){
<td>
@Html.DisplayFor(car => car.model)
</td>
}
</tr>
}
关于c# - 我如何使用存储库模式的预加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38126283/