使用 linq 将一对多关系转换为查找

Kin*_*sin 3 c# linq lookup

在我的数据库中,我有一个定义了一对多关系的条目。

我只想要一个简单的Lookup设定关系。

简单的例子:

汽车的值(如制造商和类型)位于同一个表中,属性(如颜色、马力、发动机)在另一个表中定义。(这只是一个例子,从数据库的角度来看没有意义)。

我想要的只是选择所有汽车,例如Ford通过它们的属性进行查找,但我不明白这一点。

目前我有

dbContext.Cars
    .Where(c => c.Manufacturer == "Ford")
    .Select(c => new {
        c.Type,
        Attributes = c.Attributes.Select(a => new{
            a.Value
        })
    })
    .ToLookup(arg => arg.Attributes.Select(a => a.Value), arg => arg.Type);
Run Code Online (Sandbox Code Playgroud)

但这给出了一个奇怪的组合查找

我需要像这样的查找

[500hp] : {Type1,Type2}
[300hp] : {Type3,Type6}
[green] : {Type3,Type7}
[blue] : {Type2,Type1}
Run Code Online (Sandbox Code Playgroud)

Gil*_*een 5

我假设你需要的是SelectMany:

dbContext.Cars
    .Where(c => c.Manufacturer == "Ford")
    .SelectMany(c => c.Attributes.Select(a =>new { c.Type, a.Value }))
    .ToLookup(arg => arg.Value, arg => arg.Type);
Run Code Online (Sandbox Code Playgroud)