Entity Framework ISNULL in Where condition

.net c# entity-framework isnull

Question

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
5
12/22/2013 4:22:04 AM

Accepted Answer

Try something like

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

17
12/19/2013 2:06:34 PM

Popular Answer

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'


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow