[英]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.