Edward
Edward

Reputation: 37

LINQ conditional query where value might be null

I'm trying to write a query to select data from database. I have the following code :

 from notes in ctx.Notes
 .Where(x => x.UserId== user.UserId 
 || x.UserId == user.FamilyId 
 || x.UserId == user.CompanyId).DefaultIfEmpty()

The problem with this is that the FamilyId and CompanyId are both nullable types and may not have any value at all which corrupts the whole query. How can I rewrite it so it only looks for FamilyId/CompanyId if they have values?

Upvotes: 1

Views: 1452

Answers (2)

Shivam Mishra
Shivam Mishra

Reputation: 317

Simple, just add an AND clause to check if it's not null:

 from notes in ctx.Notes.Where(x => x.UserId== user.UserId || (user.FamilyId ! =null && x.UserId == user.FamilyId) || (user.CompanyId !=null && x.UserId == user.CompanyId)).DefaultIfEmpty()

Upvotes: 0

Backs
Backs

Reputation: 24903

Create condition query:

var users = ctx.Notes.Where(x => x.UserId == user.UserId);

if (user.FamilyId != null)
{
    users = users.Union(ctx.Notes.Where(x => x.UserId == user.FamilyId));
}

if (user.CompanyId != null)
{
    users = users.Union(ctx.Notes.Where(x => x.UserId == user.CompanyId ));
}

var result = users.ToArray();

Upvotes: 5

Related Questions