[英]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.