【问题标题】:How to Select distinct row in entity framework如何在实体框架中选择不同的行
【发布时间】:2020-05-14 23:25:19
【问题描述】:
我在 sql server 中使用以下命令来获取数据:
Select distinct ConstituentGroupNameId,UserId,CreatedTime from dbo.ConstituentRecords
但我无法通过实体框架实现它。我正在尝试获取唯一的 ConstituentGroupNameId 和其他字段。
【问题讨论】:
标签:
asp.net
asp.net-mvc
asp.net-mvc-3
entity-framework-6
entity
【解决方案1】:
您可以在 Linq 查询中简单地使用 groupby。它可以达到与T-SQL的distinct操作相同的结果。
首先要区分的组字段,您可以获取您创建的组。然后选择组中的第一个项目。
最后,您将获得您过滤的不同行。
Lambda 表达式:
var boo = ConstituentRecords
.GroupBy(o => new { o.ConstituentGroupNameId, o.UserId, o.CreatedTime } )
.Select(g=>g.First())
.ToList();
或
查询表达式:
var boo = (from v in ConstituentRecords
group v by new { v.ConstituentGroupNameId, v.UserId, v.CreatedTime } into g
select g.First()).ToList();