How to check if object is null in EF

依然范特西╮ 提交于 2020-03-06 06:22:36

问题


I am new to EF and trying to do a small project with it. I added a condition to EF but I am having a problem. My condition is all about IN condition like SQL, SELECT * FROM table1 WHERE col1 IN (1,2,3...)

Here is my EF....

var res3 = res2.Where(l => !slitDetail
                        .Any(s => s.BlockId == l.Id 
                               && s.WarehouseDepot.WarehouseDepotName != "Ara Ürün Depo" 
                               && s.WarehouseDepot.WarehouseDepotName != "Özel Kesim Depo"));

s.WarehouseDepot might be NULL sometimes which is normal, but if it is null, this query throws an exception.

How can I check if s.WarehouseDepot is null and make it work even if it is null?


回答1:


There are 2 possiblities if s.WarehouseDepot == null

1) You want your Any to return true, in that case you could use something like

var res3 = res2.Where(l => !slitDetail
                        .Any(s => s.BlockId == l.Id
                               && s.WarehouseDepot != null
                                ? (s.WarehouseDepot.WarehouseDepotName != "Ara Ürün Depo" && s.WarehouseDepot.WarehouseDepotName != "Özel Kesim Depo") 
                                : true));

This would use the s.WarehouseDepot only if it has a value otherwise it would return true

2) You want your Any to return false. In this case you could simply replace the true by false in the above expression or use something like

var res3 = res2.Where(l => !slitDetail
                        .Any(s => s.BlockId == l.Id
                               && s.WarehouseDepot != null
                               && s.WarehouseDepot.WarehouseDepotName != "Ara Ürün Depo"
                               && s.WarehouseDepot.WarehouseDepotName != "Özel Kesim Depo"));

Note that both these outcomes will automatically consider the s.BlockId == l.Id condition too.



来源:https://stackoverflow.com/questions/36883787/how-to-check-if-object-is-null-in-ef

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