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