[英]How to perform a join in c# .net core Entity Framework using
I have this relation ship. 我有这种关系。
In both of this model I have a navigation properties, however I still don't know how to use them. 在这两个模型中,我都有一个导航属性,但是我仍然不知道如何使用它们。
The Customer Model 客户模型
public class Customer
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int CustomerGroupId { get; set; }
public CustomerGroup CustomerGroup { get; set; }
}
Customer Group Model 客户群模型
public class CustomerGroup
{
public int Id { get; set; }
public string Name { get; set; }
public List<Customer> Customers { get; set; }
}
I want to display a list of customers along with their customer group name. 我想显示客户列表及其客户组名称。
I have this query but its only giving the customer groups list but not the customers. 我有此查询,但它只提供客户组列表,但没有客户。
Changes to new query executing. 更改为执行新查询。
what im getting as a return 我得到什么回报
The CustomerGroup is null. CustomerGroup为空。
如果您同时希望组及其客户,则需要告诉EF包括导航属性:
db.CustomerGroups.Include(g => g.Customers).ToListAsync()
Get all customers and in the view, when you loop through the list of customers , simply access the CustomerGroup
navigational property of each item. 获取所有客户,并在视图中循环浏览客户列表时,只需访问每个项目的CustomerGroup
导航属性。
var customers = db.Customers.ToList();
return View(customers);
and in the view 并认为
@model List<Customer>
@foreach(var c in Model)
{
<p>@c.FirstName </p>
<p>@c.CustomerGroup.Name</p>
}
Make sure your CustomerGroup
property is virtual
确保您的CustomerGroup
属性是virtual
public class Customer
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int CustomerGroupId { get; set; }
public virtual CustomerGroup CustomerGroup { get; set; }
}
Keep in mind that this will do lazy loading. 请记住,这会延迟加载。 To do eager loading (a single query to get everything), you may consider using a view model and project to that. 要进行急切的加载(一个查询即可获取所有内容),您可以考虑使用视图模型并对此进行投影。
So create a view model 因此创建一个视图模型
public class CustomerVm
{
public string FirstName { set;get;}
public string GroupName { set;get;}
}
and in your GET action project your LINQ query result to a collection of this view model. 在您的GET操作项目中,您的LINQ查询结果将成为该视图模型的集合。
var customerVms = db.Customers
.Select(x=> new CustomerVm { FirstName = x.Name,
GroupName =x.CustomerGroup.Name})
.ToList();
return View(customerVms );
Make sure your view is now strongly typed to a list of CustomerVm's. 确保您的视图现在已严格键入到CustomerVm的列表中。
@model List<CustomerVm>
@foreach(var c in Model)
{
<p>@c.FirstName </p>
<p>@c.GroupName</p>
}
Add other properties to your view model as needed by the view. 根据视图的需要将其他属性添加到视图模型。
Take a look at this post for understanding the difference between eager loading vs lazy loading 看看这篇文章 ,了解渴望加载与延迟加载之间的区别
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.