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

前端 未结 2 362
梦谈多话
梦谈多话 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<Product> Products {get; set;}
    }
    

    In action collect data:

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

    And In view:

    @model IEnumerable<ProductUserViewModel>
    
    foreach(var item in Model)
    {
       <li>@item.User.Name</li>
       foreach(var product in item.Products)
       {
         <li>@product.Name</li>
       }
    }
    
    0 讨论(0)
  • 2021-01-26 04:00

    You can query the children and group them by their parent name. This assumes a ParentClient=>Client relationship.

    var clientGroups = context.Clients.GroupBy(x => x.ParentClient.Name).OrderBy(x=>x.Key).ToList();
    
            foreach (var clientGroup in clientGroups)
            {
                var parentName = clientGroup .Key;
    
                foreach (var child in clientGroup)
                {
                    var title = child.Name;
                }
            }
    
    0 讨论(0)
提交回复
热议问题