2011-08-01 31 views
4

我有DbSet對象DbSet<ShippingInformation> ShippingInformations;我也覆蓋了ShippingInformation的equals運算符。查找對象是否存在Dbset

如何找到是否存在一個現有對象y,其集合ShippingInformations與對象x相等,都是ShippingInformation

到目前爲止,我曾嘗試:

storeDB.ShippingInformations.Contains(shippingInformation); 

然而,這僅適用於基本類型。

回答

7

不幸的是,您不能在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>>)。

+0

如果我有十個領域進行比較,是否有一個更好的方法來做到這一點,而不是把它放在一個表達式? – Seth

+0

這會在多個地方使用嗎?因爲如果它不會,只有一個查詢是相當整潔的(我認爲)。您可以將其聲明爲靜態字段並[提前編譯](http://msdn.microsoft.com/en-us/library/bb399335.aspx),以便更高性能。 –

+0

很可能不止一個地方。你是什​​麼意思「將它聲明爲靜態字段」?你的意思是聲明一個方法來進行比較作爲一種靜態方法並指出這一點? – Seth

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

或者這也應該工作,如果你重寫equals運算符。

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

這不僅僅是比較對象id嗎? – Seth

+1

您可以比較任何內容,以Ids爲例。 –

+0

第二個例子將**不工作,因爲實體框架將不得不反編譯你的'Equals'實現來看它是如何完成的(當然它不)。另外,你甚至不會在這裏調用'Equals'('=='默認比較引用,除非被覆蓋)。 –

1

試試這個:

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

,你可能還需要實現IEqualityComparer讓你在找什麼。

+0

這將從數據庫中帶出整個「ShippingInformations」表。 –

+0

另外,實現'IEqualityComparer'對Entity Framework查詢沒有任何好處(假設你不是真的要將整個表加載到內存中,然後對它執行LINQ to Objects)。 –

+0

@丹感謝您的意見。 – Seth