c# - 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(),
它抛出了一个异常
解决方案
在解释 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
*/
推荐阅读
- javascript - 在 javascript 类中,我如何 super() 所有现有参数?
- c# - 错误弹出应用程序无法安装,因为它的完整性 iphone Xamarin 形式
- arrays - 将 char 指针的地址分配给 int
- python - python如何将序数添加到熊猫数据框中
- java - 错误:处理 POM 时遇到一些问题:
- sql - 在 SQL 中将 DATETIME 转换为 varchar
- r - 如何在将重复项放在一起的同时对分组行进行排序
- sql-server - 获取数据库在过去 24 小时内执行的所有存储过程的计数
- java - 有人可以直观地向我解释这段代码(找到没有溢出错误的 nCr)吗?
- python - Python 硒点击()