繁体   English   中英

查找 Dbset 中是否存在对象

[英]Find if Object Exists in Dbset

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

我怎样才能找到一个现有的对象, y 在等于对象 x 的集合ShippingInformations中,两者都是ShippingInformation类型。

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

storeDB.ShippingInformations.Contains(shippingInformation);

但是,这只适用于原始类型。

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

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

(我只是为了展示这个想法而制作了这些字段, other是您正在寻找的ShippingInformation 。)

如果有很多地方要重用这个表达式,你可能想用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

这样的代码应该放在数据层。

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

bool ifExists = storeDB.ShippingInformations.Any(shi=>shi.Id == objectYouWantToCompareTo.Id);

或者,如果您覆盖 equals 运算符,这也应该有效。

bool ifExists = storeDB.ShippingInformations.Any(shi=>shi == objectYouWantToCompareTo);

试试这个:

storeDB.ShippingInformations.ToList().Contains(shippingInformation);

您可能还必须实现IEqualityComparer才能获得所需的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM