且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

查找对象是否存在于Dbset中

更新时间:2023-11-26 08:05:52

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

Unfortunately you can't use your Equals implementation in a query to EF because it can't decompile your code to see how it's done. You should be fine using Any method with a predicate expression:

bool exists = storeDB.ShippingInformations
    .Any(info =>
            info.CustomerID == other.CustomerID
            && info.CountryID == other.CountryID
        );

(我整理了这些字段只是为了说明这个主意,other是您要查找的ShippingInformation.)

(I made the fields up just to show the idea, other is the ShippingInformation you're looking for.)

如果要在许多地方重复使用此表达式,则可能要使用 LinqKit 组合表达式:

If there are many places where you want to re-use this expression, you might want to use LinqKit to combine expressions:

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

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

Such code should be placed in data layer.

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

I'm not 100% sure if the above code works though. It may very well be that EF won't allow "other" object to be used in the query expression. If this is the case (please let me know), you'll have to modify the expression to accept all primitive type values for comparison (in our example, it would've become Expression<Func<ShippingInformation, int, int, bool>>).