How to get parent and child table title using nest

2019-03-03 09:33发布

问题:

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:

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

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

thanks

回答1:

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


回答2:

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