【问题标题】:Distinct using one property and not entire object [duplicate]使用一个属性而不是整个对象来区分[重复]
【发布时间】:2015-02-11 01:39:36
【问题描述】:

我正在使用 C# / Entity Framework 并尝试将 Distinct() 与一个属性一起使用,但我找不到正确的语法。

我有什么:

context
.Orders
.Select(o => o.User)
.Distinct();

最后的查询是对整个 User 对象做一个 distinct:

SELECT 
    [Distinct1].[ID] AS [ID], 
    [Distinct1].[Name] AS [Name], 
    [Distinct1].[Email] AS [Email], 
    (...)

我需要的是仅使用一个属性来区分,例如名称。最终查询类似于:

SELECT 
    [ID], 
    [Distinct1].[Name] AS [Name], 
    [Email], 
    (...)

如果我在Distinct() 之前使用ToList(),我可以在Distinct() 中使用EqualityComparer,但我试图避免它,因为我遇到了性能问题,因为它正在加载高负载信息进入内存而不是在数据库中过滤。

【问题讨论】:

标签: c# .net entity-framework


【解决方案1】:

尝试使用比较器:

public class UserComparer : IEqualityComparer<User>
{
    public bool Equals(User x, User y)
    {
        return (x.Name == y.Name);
    }

    public int GetHashCode(User user)
    {
        return user.GetHashCode();
    }
}

context.Orders.Select(o => o.User).Distinct(new UserComparer());

我的猜测是实体框架应该基于 Name 而不是整个对象。

【讨论】:

    猜你喜欢
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2021-03-28
    • 2022-08-24
    相关资源
    最近更新 更多