C# 查找Dbset中是否存在对象
我有一个C# 查找Dbset中是否存在对象,c#,.net,linq,C#,.net,Linq,我有一个DbSet对象DbSet发货信息我还为ShippingInformation重写了equals运算符 如何查找集合ShippingInformations中是否存在与对象x相等的现有对象y,这两种类型均为ShippingInformation 到目前为止,我已经尝试: storeDB.ShippingInformations.Contains(shippingInformation); 但是,这只适用于基本类型 bool ifExists = storeDB.ShippingInfor
DbSet
对象DbSet发货信息代码>我还为ShippingInformation重写了equals
运算符
如何查找集合ShippingInformations
中是否存在与对象x相等的现有对象y,这两种类型均为ShippingInformation
到目前为止,我已经尝试:
storeDB.ShippingInformations.Contains(shippingInformation);
但是,这只适用于基本类型
bool ifExists = storeDB.ShippingInformations.Any(shi=>shi.Id == objectYouWantToCompareTo.Id);
或者,如果重写equals运算符,这也应该起作用
bool ifExists = storeDB.ShippingInformations.Any(shi=>shi == objectYouWantToCompareTo);
试试这个:
storeDB.ShippingInformations.ToList()包含(shippingInformation)代码>
您可能还必须实现一个来获取所需内容。不幸的是,您不能在对EF的查询中使用您的Equals
实现,因为它无法反编译您的代码以查看它是如何完成的。您可以使用带有谓词表达式的Any
方法:
bool exists = storeDB.ShippingInformations
.Any(info =>
info.CustomerID == other.CustomerID
&& info.CountryID == other.CountryID
);
(我把这些字段拼凑起来只是为了表明我的想法,other
是您要查找的ShippingInformation
)
如果有许多地方需要重复使用此表达式,则可能需要使用来组合表达式:
private static Expression<Func<ShippingInformation, ShippingInformation, bool>>
isEqualExpr =
(info, other) =>
info.CustomerID == other.CustomerID
&& info.CountryID == other.CountryID;
// somewhere down this class
var expr = isEqualExpr; // reference the expression locally (required for LinqKit)
bool exists = storeDB.ShippingInformations
.Any(x => expr.Invoke(x, other)); // "injects" equality expression
私有静态表达式
等质量=
(信息,其他)=>
info.CustomerID==其他.CustomerID
&&info.CountryID==其他.CountryID;
//在这个班下面的某个地方
var expr=isEqualExpr;//本地引用表达式(LinqKit需要)
bool exists=storeDB.ShippingInformations
.Any(x=>expr.Invoke(x,其他));//“注入”等式表达式
这样的代码应该放在数据层中
我不能100%确定上述代码是否有效。很可能是EF不允许在查询表达式中使用“other”对象。如果是这种情况(请让我知道),您必须修改表达式以接受所有原语类型值进行比较(在我们的示例中,它将变成表达式
)。这不是只比较对象ID吗?您可以比较任何东西,Ids就是一个例子。第二个例子不起作用,因为实体框架必须对Equals
实现进行反编译,才能看到它是如何完成的(当然不会)。此外,您甚至没有在此处调用Equals
(=
默认情况下比较引用,除非被重写)。@Dan he确实做了注释以重写Equals运算符。@Seth:重写(我假设您这样做了)和(很少需要这样做,如果有的话)之间有区别。如果仅覆盖Equals
,则第二个示例将不起作用(并且在实体框架的上下文中,storeDB.ShippingInformations
,由于上述原因将根本不起作用)。这将从数据库中获取整个ShippingInformations
表。此外,实现IEqualityComparer
对实体框架查询没有好处(假设您不打算在内存中加载整个表,然后对其上的对象执行LINQ)。如果我有十个字段要比较,有没有一种更简洁的方法来代替将所有内容都放在一个表达式中?这种方法会在多个地方使用吗?因为如果它不会,那么仅仅一个查询就相当简洁了(我认为)。您可以将其声明为静态字段,因此它的性能更高。很可能不止一个位置。“声明为静态字段”是什么意思?你是说声明一个进行比较的方法作为静态方法并指向它?