开发者

Find if Object Exists in Dbset

开发者 https://www.devze.com 2023-03-24 04:55 出处:网络
I have a DbSet object DbSet<ShippingInformation> ShippingInformations; I have also overridden the equals operato开发者_Go百科r for ShippingInformation.

I have a DbSet object DbSet<ShippingInformation> ShippingInformations; I have also overridden the equals operato开发者_Go百科r 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);

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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号