简体   繁体   中英

Find if Object Exists in Dbset

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.

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

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

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

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

try this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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