I have this Linq query:
IQueryable<SPR> query = db.SPRs;
if (!string.IsNullOrEmpty(search.accountNumber))
{
query = query.Where(b => b.CustomerAccountNumber.Contains(search.accountNumber));
}
if (!string.IsNullOrEmpty(search.accountName))
{
query = query.Where(b => b.CustomerNumber.Contains(search.accountName));
}
if (!string.IsNullOrEmpty(search.submittedBy))
{
query = query.Where(b => b.SubmittedBy.Contains(search.submittedBy));
}
if (!string.IsNullOrEmpty(search.smName))
{
query = query.Where(b => b.SMUserName == search.smName);
}
var result = query.ToList();
I am just appending the where clause if conditions are true. The issue is that it is not just adding a And in the generated SQL where clause like I want it to.
Here is the generated SQL if I have the SubmittedBy and SMUserName filled with data.
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[CustomerNumber] AS [CustomerNumber],
[Extent1].[CustomerAccountNumber] AS [CustomerAccountNumber],
[Extent1].[SMUserName] AS [SMUserName],
[Extent1].[SubmittedBy] AS [SubmittedBy],
[Extent1].[Notes] AS [Notes]
FROM
[dbo].[SPRs] AS [Extent1]
WHERE
([Extent1].[SubmittedBy] LIKE @p__linq__0 ESCAPE N'~')
AND (([Extent1].[SMUserName] = @p__linq__1) OR (([Extent1].[SMUserName] IS NULL)
AND (@p__linq__1 IS NULL)))
Not sure how this last line OR (([Extent1].[SMUserName] IS NULL) AND (@p__linq__1 IS NULL))) is getting added which is messing the query up.
Can someone please tell me how I can have just AND in the eventual query when the if conditions are satisfied?
b.SMUserName == search.smNamein c# can be true if both arenull, it's not the case for SQL hence it requires an additional check.(([Extent1].[SMUserName] IS NULL) AND (@p__linq__1 IS NULL))will always be false since @p__linq__1 will never be null due to!string.IsNullOrEmpty(search.smName).