Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if Object Exists in Dbset

Tags:

c#

.net

linq

I have a DbSet object DbSet<ShippingInformation> ShippingInformations; I have also overridden the equals operator for 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.

like image 365
Seth Avatar asked Aug 01 '11 22:08

Seth


3 Answers

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
        );

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

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.

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>>).

like image 124
Dan Abramov Avatar answered Nov 19 '22 22:11

Dan Abramov


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

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

bool ifExists = storeDB.ShippingInformations.Any(shi=>shi == objectYouWantToCompareTo);
like image 24
AD.Net Avatar answered Nov 19 '22 22:11

AD.Net


try this:

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

you may also have to implement a IEqualityComparer to get what you're looking for.

like image 1
David Wick Avatar answered Nov 19 '22 20:11

David Wick