Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not null in LINQ query still return null records? [closed]

Tags:

c#

.net

linq

Why does the LINQ query return records that are null? I'm using the code below to no avail.

var list = (from t in dal.table
            where t.name != null);
like image 961
MdeVera Avatar asked Jul 21 '11 22:07

MdeVera


People also ask

Does LINQ ever return NULL?

It will return an empty enumerable. It won't be null.

How do you handle NULL in LINQ query?

Maybe you can just use Where(q => q != null) , to filter out the nulls? If you can, just modify GetAttendanceListOf to return empty list if nothing is found for the given 'roll-no'.

IS NOT NULL check in LINQ?

The query needs to look for the values that is not null in any one of the list values (100 or 110 or 120). model = (from line in db. Bibs where line. TNo == "245" && (line.

Is NULL SQL in LINQ?

NULL in SQL means, "value absent, will match any comparison", whereas null in . NET means "no object, comparing against null will always yield false".


3 Answers

You forgot to select.

var list = (from t in dal.table
            where t.name != null
            select t);
like image 63
BoltClock Avatar answered Oct 19 '22 03:10

BoltClock


I encountered the same strange behavior. The C# code is

public DbSet<Document> Documents { get; set; }
List<Document> = Documents
    .Where(d => d.BusinessId = 818)
    .Where(d => d.CurrencyId != null)
    .ToList();

but the SQL statement generated is this:

exec sp_executesql N'SELECT 
[Extent1].[DocumentId] AS [DocumentId], 
[Extent1].[DateCreated] AS [DateCreated],
...
FROM [dbo].[Documents] AS [Extent1]
WHERE [Extent1].[BusinessId] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=818    

Clearly LINQ ignores the .Where(d => d.CurrencyId != null) clause.

My solution was as follows:

List<Document> = Documents
    .Where(d => d.BusinessId = 818)
    .ToList() // <== Gel all documents and filter in memory
    .Where(d => d.CurrencyId != null)
    .ToList();

Note: Technically we move the NOT Null filter from Linq-To-Sql to Linq-To-objects.

Very inefficient since we select ALL the documents into memory and filter there (instead of filtering in the db-level).

I my case the number of records is usually small so the solution worked for me.

like image 28
Dror Avatar answered Oct 19 '22 03:10

Dror


101 C# LINQ Examples: http://msdn.microsoft.com/en-us/vcsharp/aa336746

like image 1
Chris Hawkins Avatar answered Oct 19 '22 04:10

Chris Hawkins