简体   繁体   English

在视图中使用嵌套的foreach的MVC实体框架

[英]MVC Entity Framework using a nested foreach in view

I'm passing 3 sets of data through to a view in a viewmodel and have a problem relating one of them to the other two in my foreach coding: 我正在将3组数据传递到视图模型中的视图,并在我的foreach编码中将其中一组与另外两组相关联:

My DB tables are: "ServiceGroups" is parent to "Services" "Services" is related through a joining table (using a 2 composite Primary Key) to the aspnet_users table (I call "Users") 我的数据库表是:“ ServiceGroups”是“ Services”的父级“ Services”通过连接表(使用2个复合主键)与aspnet_users表(我称为“ Users”)相关

I pulled this into an EF model called GWServices.edmx 我将其放入名为GWServices.edmx的EF模型中

so now I have 3 entities related like so: ServiceGroup (parent to) Service Service (many to many with) User 所以现在我有3个相关的实体,如下所示:ServiceGroup(父级)Service Service(很多)

Then I created a controller and a viewmodel like this: 然后我创建了一个控制器和一个像这样的视图模型:

{

    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));
        }

    }
}

Next I created the view with 3 foreach loops to: 接下来,我创建了带有3个foreach循环的视图,以:

  1. Get and present as a UL, a list of all service groups in the database (which worked) 获取并以UL的形式呈现数据库中所有服务组的列表(有效)
  2. Populate a table under each Servicegroup filling down some Service data for each Service within that given group (which also work) 在每个服务组下填充一个表格,为该给定组内的每个服务填充一些服务数据(也可以使用)
  3. Test whether the user is associated with this particular Service, if so show only the red cross icon, otherwise show the green "select me" icon. 测试用户是否与该特定服务相关联,如果是,则仅显示红色叉形图标,否则显示绿色的“选择我”图标。 (this doesn't populate any users) (这不会填充任何用户)

So the code looks like this: 因此,代码如下所示:

<% 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> 
<% } %>

Can anyone tell me why foreach(var user in serv.user) does not recognise that "Customer1" (the currently logged in user) has 6 services ordered (as it is in the joining table)? 谁能告诉我为什么foreach(serv.user中的var用户)无法识别“ Customer1”(当前登录的用户)订购了6项服务(就像在联接表中一样)?

Thanks! 谢谢!

Paul 保罗

Looking at your code I think this could be resolved by loading the child tables of ServiceGroups. 查看您的代码,我认为可以通过加载ServiceGroups的子表来解决。

It is likely that the Services & User reference was not loaded in the original Entity Framework query. 原始实体框架查询中可能未加载“服务和用户”引用。 Therefore, as you are trying to iterate through the children in the foreach loop, it does not see a collection, it just sees null. 因此,当您尝试在foreach循环中遍历子级时,它看不到集合,而只会看到null。

You should try altering your retrieval statements: 您应该尝试更改检索语句:

_db.ServiceGroupSet.ToList()

to

_db.ServiceGroupSet.Include("ServiceSet").Include("UserSet").ToList()

If this doesn't fix your issue, I would put a break point on the below line of code and traverse the List to see if it has the data you expect. 如果这不能解决您的问题,我会在下面的代码行上放置一个断点,然后遍历List来查看它是否具有您期望的数据。

this.ServiceGroups = servicegroups; 

For starters, username comparisons are generally case-insensitive. 首先,用户名比较通常不区分大小写。 So this: 所以这:

          <%if (user.UserName == User.Identity.Name)

...should be: ...应该:

          <%if (user.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase))

You also have a bug where you don't dispose your entity context. 您还有一个错误,您不处理实体上下文。 You should override Controller.Dispose and dispose it there. 您应该重写Controller.Dispose并将其处置在那里。 This allows the view to render before the context is disposed. 这允许视图在处理上下文之前进行渲染。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM