[英]MVC Entity Framework using a nested foreach in view
我正在将3组数据传递到视图模型中的视图,并在我的foreach编码中将其中一组与另外两组相关联:
我的数据库表是:“ ServiceGroups”是“ Services”的父级“ Services”通过连接表(使用2个复合主键)与aspnet_users表(我称为“ Users”)相关
我将其放入名为GWServices.edmx的EF模型中
所以现在我有3个相关的实体,如下所示:ServiceGroup(父级)Service Service(很多)
然后我创建了一个控制器和一个像这样的视图模型:
{
public class ServicesViewModel
{
public ServicesViewModel(List<ServiceGroup> servicegroups, List<Service> services, List<User> aspnetusers)
{
this.ServiceGroups = servicegroups;
this.Service = services;
this.AspnetUsers = aspnetusers;
}
public List<ServiceGroup> ServiceGroups { get; set; }
public List<Service> Service { get; set; }
public List<User> AspnetUsers { get; set; }
}
public class ClientServicesController : Controller
{
public ActionResult Index()
{
GWEntities _db = new GWEntities();
var servicegroups = _db.ServiceGroupSet.ToList();
var services = _db.ServiceSet.ToList();
var aspnetusers = _db.UserSet.ToList();
return View(new ServicesViewModel(servicegroups, services, aspnetusers));
}
}
}
接下来,我创建了带有3个foreach循环的视图,以:
因此,代码如下所示:
<% foreach (var servgroup in Model.ServiceGroups) { %>
<ul> <%= servgroup.ServiceGroupName%> </ul>
<table>
<% foreach (var serv in servgroup.Service)
{ %>
<tr>
<td class="td1">
<%= serv.ServiceDescription%>
</td>
<td class="td2">
<% = Html.Encode(String.Format("{0:f}",serv.MonthlyPrice)) %>
</td>
<td class="td3">
<%foreach (var user in serv.User) {%>
<%if (user.UserName == User.Identity.Name)
{ %>
<img src="/Content/LightRedCross_2.png" alt="" height="15px" width="15px"/>
<% }
else
{%>
<img src="/Content/LightGreenAdd_2.png" alt="" height="15px" width="15px"/>
<%} %>
<%} %>
</td>
</tr>
<% } %>
</table>
<% } %>
谁能告诉我为什么foreach(serv.user中的var用户)无法识别“ Customer1”(当前登录的用户)订购了6项服务(就像在联接表中一样)?
谢谢!
保罗
查看您的代码,我认为可以通过加载ServiceGroups的子表来解决。
原始实体框架查询中可能未加载“服务和用户”引用。 因此,当您尝试在foreach循环中遍历子级时,它看不到集合,而只会看到null。
您应该尝试更改检索语句:
_db.ServiceGroupSet.ToList()
至
_db.ServiceGroupSet.Include("ServiceSet").Include("UserSet").ToList()
如果这不能解决您的问题,我会在下面的代码行上放置一个断点,然后遍历List来查看它是否具有您期望的数据。
this.ServiceGroups = servicegroups;
首先,用户名比较通常不区分大小写。 所以这:
<%if (user.UserName == User.Identity.Name)
...应该:
<%if (user.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase))
您还有一个错误,您不处理实体上下文。 您应该重写Controller.Dispose
并将其处置在那里。 这允许视图在处理上下文之前进行渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.