【问题标题】:Entity framework distinct but not on all columns实体框架不同但并非在所有列上
【发布时间】:2013-08-07 16:39:22
【问题描述】:

我想通过实体框架进行查询,该框架将两个不同表中的联系人联合起来,删除重复项和按日期排序。我遇到的问题是不同的日期使相同的联系人看起来是唯一的。我不想在不同的日期中包含日期,但之后我确实需要它来进行订购。我不能先进行排序,删除日期然后执行 distinct,因为 distinct 会改变排序。我也不能在联合之前订购,因为这并不能确保在联合之后订购。

我想区分除日期以外的所有字段,日期仅在订购时需要。

理想情况下,我会将比较器传递给 distinct,但 EF 无法将其转换为 SQL。

db.Packages.Select(p => new Recent()
{
    Name = p.Attention, Address1 = p.Address1, ... , Date = ShippingDate
})
.Concat(db.Letters.Select(l => new Recent()
{
    Name = l.AddressedTo, Address1 = p.Address1, ..., Date = MarkedDate
})
.Distinct()
.OrderByDescending(r => r.Date);

或 SQL 中的问题

SELECT DISTINCT Attention, Address1, ShippingDate
FROM Packages
UNION ALL
SELECT AddressedTo, Address1, MarkedDate
FROM Letters
ORDER BY ShipmentDate DESC

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    你应该能够使用 GroupBy 来做你想做的事,就像这样(更不用说Group By is more performant than Distinct in EF):

    db.Packages.Select(p => new Recent()
    {
        Name = p.Attention, Address1 = p.Address1, ... , Date = ShippingDate})
    .Concat(db.Letters.Select(l => new Recent()
    {
        Name = l.AddressedTo, Address1 = p.Address1, ..., Date = MarkedDate}))
    .GroupBy(p => <parameters to group by - which make the record distinct>)
    .Select(g => new {Contact = g.Key, LastShippingDate = g.Max(p => p.ShippingDate)});
    

    【讨论】:

      【解决方案2】:

      我会担心这种方法,即使 distinct 可能会删除其中一个项目并让您在这两个项目中随机选择日期,然后您的排序将完全不可预测。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-12
        相关资源
        最近更新 更多