【发布时间】:2020-04-24 17:38:12
【问题描述】:
我想根据一个属性从数据库中选择不同的值,并在该属性为null 时返回所有值。 IDs 在我的数据库中是 Strings
我的数据库如下所示:
Id1 Id2 Value
____________________
1 null Value1
2 1 Value2
3 1 Value3
4 null Value4
5 null Value5
6 2 Value6
7 2 Value7
8 2 Value8
我想从我的查询中得到这样的输出:
Id1 Id2 Value
____________________
1 null Value1
2 1 Value2 // i dont care which one from Id2 = 1 i get
4 null Value4
5 null Value5
6 2 Value6 // i dont care which one from Id2 - 2 i get
如您所见,我想获得一个 List,它包含 Id2 为空的所有元素,并且只返回一个 Id2 相同的元素(我不关心将返回哪个元素查询)。
我尝试编写一些代码:
query
.Where(x => !string.IsNullOrEmpty(x.Id2))
.GroupBy(z => z.Id2)
.Select(grp => grp.FirstOrDefault())
.ToListAsync();
但我没有得到我想要的,只有一个由Id2 表示的项目和只有一个null 值,像这样:
Id1 Id2 Value
____________________
1 null Value1
2 1 Value2 // I want to get all elements where Id2 = null
6 2 Value6 // and distinct elements based on Id2
我的问题是,如何向 EF 编写查询以获取所有空项和所有基于属性的不同项?
【问题讨论】:
-
选择where not null distinct union where null?
-
说实话,我不明白你在问什么:D 我准备了我想从我的查询中得到的示例输出
标签: c# linq entity-framework-core