查找Dbset中是否存在对象

Set*_*eth 5 .net c# linq

我有一个DbSet对象DbSet<ShippingInformation> ShippingInformations;我也覆盖了equalsShippingInformation 的运算符.

如何在ShippingInformations类似于对象x 的集合中找到是否存在现有对象y ShippingInformation.

到目前为止,我尝试过:

storeDB.ShippingInformations.Contains(shippingInformation);
Run Code Online (Sandbox Code Playgroud)

但是,这仅适用于原始类型.

Dan*_*mov 8

遗憾的是,您无法Equals在对EF的查询中使用您的实现,因为它无法反编译您的代码以查看它是如何完成的.使用Any谓词表达式的方法应该没问题:

bool exists = storeDB.ShippingInformations
    .Any(info =>
            info.CustomerID == other.CustomerID
            && info.CountryID == other.CountryID
        );
Run Code Online (Sandbox Code Playgroud)

(我把这些字段用来表示想法,otherShippingInformation你正在寻找的.)

如果有许多地方要重用此表达式,您可能希望使用LinqKit组合表达式:

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
Run Code Online (Sandbox Code Playgroud)

此类代码应放在数据层中.

我不是100%确定上面的代码是否有效.很可能EF不允许在查询表达式中使用"其他"对象.如果是这种情况(请告诉我),您必须修改表达式以接受所有基本类型值进行比较(在我们的示例中,它将成为Expression<Func<ShippingInformation, int, int, bool>>).