Find if Object Exists in Dbset

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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.

回答1:

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



回答2:

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


回答3:

try this:

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

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!