我有3个数据集。 一个用于汽车(汽车),附属于一个品牌& model(AutoType)和Owner(Eigenaar)
public class Auto : BaseDbEntity
{
public string Kleur { get; set; }
public DateTime DatumGekocht { get; set; }
public string Nummerplaat { get; set; }
//relations
public Eigenaar HuidigeEigenaar { get; set; }
public AutoType HuidigeAutoType { get; set; }
}
public class AutoType : BaseDbEntity
{
public string Merk { get; set; }
public string Model { get; set; }
}
public class Eigenaar : BaseDbEntity
{
public string Voornaam { get; set; }
public string Achternaam { get; set; }
public string Naam => $"{Voornaam} {Achternaam}";
}
我试图查询以获得以下结果:
Per Merk(品牌)我想列出所有汽车(汽车)及其相应的所有者(eigenaar)。
简单地获取所有拥有相应所有者的汽车列表&品牌我有以下代码:
public List<Auto> GetAllAutosSortedByName(AutoCriteria criteria)
{
return GetFullyGraphedAutos()
.Where(x => string.IsNullOrEmpty(criteria.Name))
.OrderBy(x => x.Id).ToList();
}
private IQueryable<Auto> GetFullyGraphedAutos()
{
return _entityContext.Autos
.Include(x => x.HuidigeAutoType)
.Include(x => x.HuidigeEigenaar);
}
我的问题是我如何按品牌(merk)对它们进行分组。我尝试过这样的事情:
public List<Auto> GetAllMerkenSortedByMerk(AutoCriteria criteria)
{
return GetFullyGraphedAutos()
.Where(x => string.IsNullOrEmpty(criteria.Name))
.GroupBy(x => x.HuidigeAutoType.Merk)
.ToList();
}
显然这不起作用,但我不知道我该怎么回答这个问题。
这是一个直观的表示:顶部表格是我目前正在工作的,最下面的表格是想要的结果。
答案 0 :(得分:0)
您应该在分组操作后应用select
,但无法使用Auto
集合选择所需的数据。创建模型类来实现它;
public class GroupMerks
{
public string Merk;
public IEnumerable<Owner> Owners { get; set; }
}
public class Owner
{
public string Plate { get; set; }
public string Name { get; set; }
}
然后像这样修改查询;
public List<GroupMerks> GetAllMerkenSortedByMerk(AutoCriteria criteria)
{
return GetFullyGraphedAutos()
.Where(x => string.IsNullOrEmpty(criteria.Name))
.GroupBy(x => x.HuidigeAutoType.Merk)
.Select(x => new GroupMerks
{
Merk = x.Key,
Owners = x.Select(s => new Owner
{
Plate = s.Nummerplaat,
Name = s.HuidigeEigenaar.Achternaam
})
})
.ToList();
}
示例输出:
[
{
"Merk":"Ford",
"Owners":[
{
"Plate":"123ABC",
"Name":"John"
},
{
"Plate":"112CDE",
"Name":"Mark"
}
]
},
{
"Merk":"BMW",
"Owners":[
{
"Plate":"223ABE",
"Name":"Steve"
}
]
}
]