[英]Linq to entities group by many to many
I have 3 entities, with a many/many relationship: 我有3个实体,有很多关系:
Products -< Products_vehicles >- Vehicles 产品-<产品_车辆>-车辆
1 product can have many vehicles 1个产品可以有很多车辆
1 vehicle can have many products 1辆车可以有很多产品
As with all many/many relationships the products_vehicles class is hidden and is shown as navigation properties on the entities by EF So my classes look like this: 与所有许多关系一样,products_vehicles类是隐藏的,并且由EF在实体上显示为导航属性,因此我的类如下所示:
public partial class product
public int id { get; set; }
public string part_name { get; set; }
public virtual ICollection<vehicle> vehicles { get; set; }
public partial class vehicle
{
public int id { get; set; }
public string make { get; set; }
public string model { get; set; }
public virtual ICollection<product> products { get; set; }
I can get the products and all related vehicles easily 我可以轻松获得产品和所有相关车辆
I wish to group the products by the make, model of the vehicle, so my output would look something like this: 我希望按照车辆的制造商,型号对产品进行分组,所以我的输出看起来像这样:
product id: 5 part_name: door make: ford model: focus 产品编号:5零件名称:门品牌:福特型号:重点
product id: 5 part_name: door make: saab model: 9-3 产品编号:5零件名称:门品牌:saab型号:9-3
Is this possible? 这可能吗?
For more clarity, here's an example: 为了更加清楚,这是一个示例:
So let's say i have a product called 'bonnet' it fits 5 different vehicles: 因此,假设我有一款名为“引擎盖”的产品,它适合5种不同的车辆:
Currently i'm getting 1 product with a collection of vehicles listing all 5 above. 目前,我得到1种产品,其中包含上面列出的所有5种车辆。
I want them grouped by firstly the 'partname' (bonnet), secondly 'make' and thirdly 'model'. 我希望它们按照“零件名”(阀盖),其次“制造”和“模型”分组。 The results should be like:
结果应为:
Bonnet > Ford, Fiesta 2L
Ford, Fiesta 1.6L
Bonnet > Ford, Mondeo 2L
Ford, Mondeo 1.8L
Bonnet > Ford, Focus 1.6L
This would be very simple in SQL but i'm having a tough time getting my head around this in Linq. 这在SQL中非常简单,但是我很难在Linq中解决这个问题。
Any help greatly appreciated 任何帮助,不胜感激
I'm guessing that what you want is retrieving flat records that have selected: product id, product part name, vehicle maker and vehicle model. 我猜您想要的是检索选择的平面记录:产品ID,产品零件名称,车辆制造商和车辆型号。 If not, please ignore that answer.
如果没有,请忽略该答案。
return dbcontext.products.SelectMany(
p => p.vehicles.Select(
v => new {
product_id = p.id,
part_name = p.part_name,
make = v.make,
model = v.model
}
)
);
If you don't want to repeat product data (which would be actually quite recommended) then you might use the following approach with nested vehicles array instead: 如果您不想重复产品数据(实际上非常推荐),则可以对嵌套的车辆数组使用以下方法:
return dbcontext.products.Select(
p => new {
product_id = p.id,
part_name = p.part_name,
vehicles = p.vehicles.Select(
v => new { make = v.make, model = v.model }
}
);
dbcontext.products
is DbSet corresponding to products in your database; dbcontext.products
是与数据库中的产品相对应的DbSet; it might be called differently in your code. 在您的代码中可能会用不同的方式调用它。
Cheers~! 干杯〜!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.