How to get parent and child table title using nested foreach loop in entity framework

前端 未结 2 367
梦谈多话
梦谈多话 2021-01-26 03:26

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:

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-26 03:41

    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 Products {get; set;}
    }
    

    In action collect data:

    public ActionResult GetAllUsersAndTheirProducts()
    {
       var allUsers = db.UserTable.ToList();
    
       List result = new List();
       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);
    }
    

    And In view:

    @model IEnumerable
    
    foreach(var item in Model)
    {
       
  • @item.User.Name
  • foreach(var product in item.Products) {
  • @product.Name
  • } }

提交回复
热议问题