Entity Framework ISNULL in Where condition

落爺英雄遲暮 提交于 2020-01-14 10:27:06

问题


I have a Query in SQL Server :

SELECT * FROM MyTable t
WHERE ISNULL(t.Status,'') = ''

How I can do it in Entity Framework?

EDIT: Oh Sorry my code was like

WHERE ISNULL(t.Status,'') = ''

回答1:


Try something like

MyTable.Where( t => (t.Status ?? "") == "CO" )




回答2:


Although the question is ok, the logic isn't sound. Because if a value is equal to CO, it can never be equal to either NULL or ''. In this case you could just easily call it like this:

SQL:

SELECT * FROM MyTable t
WHERE t.Status = 'CO'

Linq:

var items = (from t in db.MyTable
             where t.Status == "CO"
             select t);

However if you would need it to have a default value when NULL and compare to that value it would make more sense (see example):

SQL:

SELECT * FROM MyTable t
WHERE ISNULL(t.Status, 'CO') = 'CO'

Linq:

var items = (from t in db.MyTable
             where (t.Status ?? "CO") == "CO"
             select t);

This would give you all items where t.Status is NULL or equal to CO. This is, of course, just an example.

Note: The generated sql would probably be slightly different, but the result is the same. It would probably look something like this:

SELECT * FROM MyTable t
WHERE COALESCE(t.Status, 'CO') = 'CO'


来源:https://stackoverflow.com/questions/20683663/entity-framework-isnull-in-where-condition

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