Linq removes where if null

What is my Linq request

var result = db.APPLICATIONS
.Where(a => Statuses.Contains(a.STATUS_ID))
.Where(a => a.TrackingNo == TrackingNo)

Statusesis an int list, and TrackingNois a value with a null int ( int?) value .

Problem: If TrackingNoit is null, I do not want to run this sentence or just skip this condition.

+4
source share
4 answers

LINQ queries can be built in several stages:

var result = db.APPLICATIONS
    .Where(a => Statuses.Contains(a.STATUS_ID));

if (TrackingNo != null)
{
    result = result.Where(a => a.TrackingNo == TrackingNo);
}

Note that if you have Select(projection), you should probably build the query in several steps in several variables:

var result2 = result.Select(a => new { STATUS_ID });

with result2"built" after if.

+4
source

nullable int, "HasValue".

var result = db.APPLICATIONS
    .Where(a => Statuses.Contains(a.STATUS_ID))
    .Where(a => a.HasValue && (a.TrackingNo == TrackingNo))

"HasValue" . HasValue false, (, , NullReferenceException). "int?", .

+2

&& null. 1 where condiiton , where.Pls :

    var result = db.APPLICATIONS
                 .Where(a => Statuses.Contains(a.STATUS_ID) 
                 && a.TrackingNo!=null 
                 && a.TrackingNo == TrackingNo)
+1

, . Statuses TrackingNo, NULLNNNOWN . IQueryable.

var result = db.APPLICATIONS.AsQueryable();

if (TrackingNo.HasValue)
{
    result = result.Where(a => Statuses.Contains(a.STATUS_ID) && a.TrackingNo == TrackingNo);
}

return result;

Alternatively, this will check if you have any statuses to apply and track separately.

var result = db.APPLICATIONS.AsQueryable();

if (Statuses != null && Statuses.Count() > 0)
{
    result = result.Where(a => Statuses.Contains(a.STATUS_ID)); 
}

if (TrackingNo.HasValue)
{
    result = result.Where(a => a.TrackingNo == TrackingNo);
}

return result;

Or the third option, as it is not clear what you really wanted. This will always apply status filtering and tracking only if available.

var result = db.APPLICATIONS.Where(a => Statuses.Contains(a.STATUS_ID));    

if (TrackingNo.HasValue)
{
    result = result.Where(a => a.TrackingNo == TrackingNo);
}

return result;
+1
source

Source: https://habr.com/ru/post/1627248/


All Articles