简体   繁体   中英

Entity Framework ISNULL in Where condition

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,'') = ''

Try something like

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

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'

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