Find if an object exists in Dbset

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

How can I find if an existing object, y, exists in the ShippingInformations set, which is equal to the x object, both are ShippingInformation types.

So far I have tried:

 storeDB.ShippingInformations.Contains(shippingInformation); 

However, this only works for primitive types.

+4
source share
3 answers

Unfortunately, you cannot use the Equals implementation in a query for EF because it cannot decompile your code to see how this is done. You should use the Any method with the predicate expression:

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

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

If there are many places where you want to reuse this expression, you can use LinqKit to combine the 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 the data layer.

I am not 100% sure if the above code works. It is possible that EF will not allow the use of a β€œdifferent” object in the query expression. If this is the case (tell me), you will need to modify the expression to accept all the values ​​of the primitive type for comparison (in our example, this would be Expression<Func<ShippingInformation, int, int, bool>> ).

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

Or this should also work if you override the equals statement.

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

try the following:

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

you may also need to run IEqualityComparer to get what you are looking for.

+1
source

All Articles