首页 > 解决方案 > Distinct 不适用于实体框架

问题描述

.Distinct()不起作用,如您所见,它返回重复的记录(具有相同的 ID )

我也试过:

Vendors = c.Item.VendorSpecifications
           .Select(v => new APVendorSimpleView { Id = v.VendorId, Name = v.Vendor.Name, Code = v.Vendor.Code })
           .GroupBy(x => x.Id)
           .Select(x => x.First())
           .ToList(),

它抛出了一个异常

IMG1 IMG2

标签: c#.netentity-frameworklinq

解决方案


在解释 Distinct 之前。您的异常感觉像是null ref exception来自v.Vendor.Name您的select APVendorSimpleView. 如果 Vendor 是null您无法访问 Name 属性并且您会遇到异常。

因为Distinct()这里是文档提到的。

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.distinct?view=netframework-4.8

如果要从某些自定义数据类型的对象序列中返回不同的元素,则必须在类中实现 IEquatable 通用接口。以下代码示例展示了如何在自定义数据类型中实现此接口并提供 GetHashCode 和 Equals 方法。

您的APVendorSimpleView模型是否符合上述标准?

public class Product : IEquatable<Product>
{
    public string Name { get; set; }
    public int Code { get; set; }

    public bool Equals(Product other)
    {

        //Check whether the compared object is null. 
        if (Object.ReferenceEquals(other, null)) return false;

        //Check whether the compared object references the same data. 
        if (Object.ReferenceEquals(this, other)) return true;

        //Check whether the products' properties are equal. 
        return Code.Equals(other.Code) && Name.Equals(other.Name);
    }

    // If Equals() returns true for a pair of objects  
    // then GetHashCode() must return the same value for these objects. 

    public override int GetHashCode()
    {

         //Get hash code for the Name field if it is not null. 
         int hashProductName = Name == null ? 0 : Name.GetHashCode();

         //Get hash code for the Code field. 
         int hashProductCode = Code.GetHashCode();

         //Calculate the hash code for the product. 
         return hashProductName ^ hashProductCode;
     }
}

//Code example
Product[] products = { new Product { Name = "apple", Code = 9 }, 
                       new Product { Name = "orange", Code = 4 }, 
                       new Product { Name = "apple", Code = 9 }, 
                       new Product { Name = "lemon", Code = 12 } };

//Exclude duplicates.

IEnumerable<Product> noduplicates =
    products.Distinct();

foreach (var product in noduplicates)
    Console.WriteLine(product.Name + " " + product.Code);

/*
    This code produces the following output:
    apple 9 
    orange 4
    lemon 12
*/

推荐阅读