查找对象是否存在于Dbset中 [英] Find if Object Exists in Dbset

查看:92
本文介绍了查找对象是否存在于Dbset中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DbSet object DbSet<ShippingInformation> ShippingInformations; I have also overridden the equals operator for ShippingInformation.

如何查找集合ShippingInformations中是否存在与对象x相等的现有对象y,它们的类型均为ShippingInformation.

How can I find if there is an existing object, y in the set ShippingInformations that is equal to object x, both of type ShippingInformation.

到目前为止,我已经尝试过:

So far I have tried:

storeDB.ShippingInformations.Contains(shippingInformation);

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

However, that only works for primitive types.

推荐答案

不幸的是,您无法在对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>>).

这篇关于查找对象是否存在于Dbset中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆