如何在实体框架使用嵌套foreach循环得到家长和孩子表题 [英] How to get parent and child table title using nested foreach loop in entity framework

查看:199
本文介绍了如何在实体框架使用嵌套foreach循环得到家长和孩子表题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父表及其子table.I必须显示在MVC项目如下页的从父和子表的标题:

I have one Parent table and its child table.I have to display title from parent and child table on page as given below in MVC project:

我知道我要使用的视图嵌套的foreach显示此数据,如如下:

I know I have to use nested foreach on view to display this data like given below:

foreach(var ptitle in parents)
{
 <li>@model.title</li>
 foreach(var pchild in parents.childs)
 {
   <li>@model.childtitle</li>
 }
}

我使用的数据库,第一种方式让会是怎样的LINQ查询来获取这种类型的结果。

I am using database first approach so what will be the linq query to get such type of result

感谢

推荐答案

假设父用户产品是他们的孩子的。这是你的实体。

Assume that parent is User and Product is their childs. Here is your entities.

public class User {
  public int Id {get; set;}
  public string Name {get; set;}
}

public class Product {
  public int Id {get; set;}
  public string Name {get; set;}

  //user who created this product
  public int UserId {get; set;}
}

您可以创建视图模型和收集你的数据显示:

You can create viewmodel and collect your data to show:

public class ProductUserViewModel {
  public User User {get; set;}
  public List<Product> Products {get; set;}
}

在行动收集数据:

public ActionResult GetAllUsersAndTheirProducts()
{
   var allUsers = db.UserTable.ToList();

   List<ProductUserViewModel> result = new List<ProductUserViewModel>();
   foreach(var user in allUsers)
   {
       ProductUserViewModel model = new ProductUserViewModel();
       model.User = user;
       model.Products = db.ProductTable.Where(e=>e.UserId == user.Id).ToList();
       result.Add(model);
   }

   return View(result);
}

和考虑:

@model IEnumerable<ProductUserViewModel>

foreach(var item in Model)
{
   <li>@item.User.Name</li>
   foreach(var product in item.Products)
   {
     <li>@product.Name</li>
   }
}

这篇关于如何在实体框架使用嵌套foreach循环得到家长和孩子表题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆