Combine multiple where conditions having optional parameters in C# linq? - c#

I am searching for a LINQ query where I have 3 parameters and two are optional parameters for this I wrote if-else conditions like below
if (id != null) { where condition}
else if (name!= null) { where condition }
else if (category != null) { where condition }
else if (id != null && name != null) { where condition }
else if (id != null && category != null) { where condition }
else if (name != null && category != null) {where condition}
else if (id != null && name != null && category != null ) { where condition }
I don't want to write more if-else conditions if there is another optional parameter added
Note. Id is not a primary key

The optimal pattern for this in EF is to add the Where conditions only conditionally. EG
IQueryable<SomeType> qry = ...;
if (id != null)
{
qry = qry.Where(x => x.Id == id);
}
if (name != null)
{
qry = qry.Where(x => x.Name == name);
}
if (category != null)
{
qry = qry.Where(x => x.Category == category);
}
var results = qry.ToList();
That way you don't clutter up the expression with lots of predicates that don't do anything, but which can mess up the query execution.

You can write it like this
id == null ? true : {id condition} &&
name == null ? true : {name condition} &&
category == null ? true: {category } and other conditions
Or
id == null || {id condition} &&
id == null || {id condition} &&
returning true will make the statement true if its value equals null.
its clean, Easy to understand and develop.
I hope it helps.

What I always do is below. Easy to read and remember.
myList
.Where(x => id == null || x.Id == id)
.Where(x => name == null || x.Name == name)
.Where(x => category == null || x.Category == category);

Related

linq multiple field search

I have EF Employee table with fields EmpNo, FirstName, LastName, Email. And to create LINQ to search all columns and return existing record. If one or more fields is null or empty the return result based on existing data. I wrote code:
public static int Search(EmployeeDt emp)
{
using (EF.Model1 context = new EF.Model1)
{
List<string> employee = context.Employees.Where(a => (a.EmpNo == null || a.EmpNo == emp.EmpNo)
&& (b => (b.FirstName == null || b.FirstName == emp.FirstName)
&& (c => (c.LastName == null || c.LastName == emp.LastName)).ToList();
return result;
}
}
But code which I tried to write isn't correct. How to write LINQ for my case?
Thanks.
You don't need reuse a=> in second condition and compare emp.FirstName with null not a variable, change your code to
List<string> employee = context.Employees.Where(a => (emp.FirstName == null || a.FirstName == emp.FirstName)
&& (emp.LastName == null || a.LastName == emp.LastName)
&& (emp.EmpNo == null || a.EmpNo == emp.EmpNo)).ToList()

Neglect variable from Query in entity framework where condition C#

public ActionResult sortFilteredItem(string sortByValue,string brand,string category,int price=0 )
{
var sortedData = (dynamic)null;
if (sortByValue != "")
{
if(sortByValue == "ltoh")
{
sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
}
}
return View(sortedData);
}
how i can neglect if price=0 from query means that it does not make any impact on EF query because if price=0 the query does not returning expected output.Because i have not any record that has 0 price so the query is always returning null.
if(price != 0)
{
sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category & x.price == price).ToList();
}
else
{
sortedData = DB.Prouducts.where(x=> x.brandName == brand & x.catName == category).ToList();
}
i have tried like this it is working good but that is lengthy process.if i have 4 or 5 more variable that,s optional so it is necessary to check null value first for working.Any recommendation ?
You can use the fllowing logic;
sortedData = DB.Prouducts.where(x=> x.brandName == brand
&& x.catName == category
&& (price == 0 || x.price == price)) //use this approach for every optional param
.ToList();
What you can do is apply filters only if the condition holds. Let's say you need to check catName and price. So:
var query = DB.Prouducts.Where(x=> x.brandName == brand);
if (category != null)
{
query = query.Where(x => x.catName == category);
}
if (price != 0)
{
query = query.Where(x => x.price == price)
}
sortedData = query.ToList();
Obviously you'll need one "if" per filter, but it is much better than considering all possible combinations.

LINQ2SQL doesn't return row if checking with null

I have following LINQ2SQL Query:
var map =
dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == tcpDms.FacilityId &&
c.DriverControlledParameterId == controlledParamId &&
c.DriverValue == value);
All the types are string.
In my DB i have a row, which must be returned by query.
When value="0", controlledParamId =null and FacilityId ="abc" this query returns null, but when i wrote following:
var test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
c.DriverControlledParameterId == null &&
c.DriverValue == "0");
test was not null
What am i doing wrong?
P.S. I also tried c.DriverControlledParameterId.Equals(controlledParamId) but it also doesn't work.
The problem is, that LINQ2SQL has a special handling for the expression c.DriverControlledParameterId == null. It is translated to the SQL DriverControlledParameterId IS NULL.
But c.DriverControlledParameterId = controlledParamId is translated to the SQL DriverControlledParameterId = :p1, even when controlledParamId is null. And in SQL DriverControlledParameterId = NULL is undefined and as such never TRUE.
How to fix: Handle the null case specifically:
TCPDriverMapping test;
if(controlledParamId == null)
test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
c.DriverControlledParameterId == null &&
c.DriverValue == "0");
else
test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
c.DriverControlledParameterId == controlledParamId &&
c.DriverValue == "0");
Or like this:
var test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
((controlledParamId == null &&
c.DriverControlledParameterId == null) ||
c.DriverControlledParameterId == controlledParamId) &&
c.DriverValue == "0");
Or like this:
IQueryable<TCPDriverMapping> query =
dbContext.TCPDriverMappings.Where(c => c.DriverFacilityId == "abc" &&
c.DriverValue == "0");
if(controlledParamId == null)
query = query.Where(c => c.DriverControlledParameterId == null);
else
query = query.Where(c => c.DriverControlledParameterId == controlledParamId);
var test = query.FirstOrDefault();
That third option is what I would use. In my opinion, this is the more readable than option 2 and has no repeated code like the first one.

Issue with LINQ IN clause when filter value is empty but works with filter values

I have a filter called serviceEntryFilter with a property System which could have values for instance EP1, EP2 OR EP1 and sometimes this filter would be null. If there are multiple values or a single value then the query (IN) clause runs fine . If the filter value is null then I get the following error:
Unable to create a constant value of type 'System.String[]'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
[HttpPost]
public ActionResult List(string ServiceEntryStatus, string ServiceEntryReconciled, string ServiceEntryReliabilityRecord, string ActiveServiceEntry,
int PageNo, ServiceEntryFilter serviceEntryFilter = null)
{
string[] systems = null;
var list = (from se in db.ServiceEntry
join r in db.RunLogEntry on se.RunLogEntryID equals r.ID into joinRunLogEntry
from r2 in joinRunLogEntry.DefaultIfEmpty()
join u in db.User on se.TechnicianID equals u.ID
join s in db.System1 on se.SystemID equals s.ID
where (
((se.RunLogEntryID == 0 || se.RunLogEntryID != null))
&& ((serviceEntryFilter.ID.HasValue == false) || (se.ID == serviceEntryFilter.ID.Value && serviceEntryFilter.ID.HasValue == true))
&& ((serviceEntryFilter.ServiceDateTime.HasValue == false) || (EntityFunctions.TruncateTime(se.ServiceDateTime) == EntityFunctions.TruncateTime(serviceEntryFilter.ServiceDateTime) && serviceEntryFilter.ServiceDateTime.HasValue == true))
&& ((serviceEntryFilter.RunDate.HasValue == false) || (EntityFunctions.TruncateTime(r2.RunDate) == EntityFunctions.TruncateTime(serviceEntryFilter.RunDate) && serviceEntryFilter.RunDate.HasValue == true))
&& ((serviceEntryFilter.Technician == null) || (u.FullName.Contains(serviceEntryFilter.Technician.Trim()) && serviceEntryFilter.Technician != null))
&& (
((ServiceEntryStatus == "O" && se.ServiceRequestClosed == false) ||
(ServiceEntryStatus == "C" && se.ServiceRequestClosed == true) ||
(ServiceEntryStatus == "A")
)
)
&& (
((ServiceEntryReliabilityRecord == null) ||
(ServiceEntryReliabilityRecord == "N" && se.ReliabilityRecord == false) ||
(ServiceEntryReliabilityRecord == "Y" && se.ReliabilityRecord == true) ||
(ServiceEntryReliabilityRecord == "A")
)
)
&& (
((ServiceEntryReconciled == null) ||
(ServiceEntryReconciled == "N" && se.Reconciled == false) ||
(ServiceEntryReconciled == "Y" && se.Reconciled == true) ||
(ServiceEntryReconciled == "A")
)
)
&& (
((ActiveServiceEntry == null) ||
(ActiveServiceEntry == "N" && se.Active == false) ||
(ActiveServiceEntry == "Y" && se.Active == true) ||
(ActiveServiceEntry == "A")
)
)
&& (
(s.PlatformID == platformID) || (platformID == 0)
)
&& ((serviceEntryFilter.System == null) || ((serviceEntryFilter.System != null) && systems.Contains(s.SystemFullName)))
)
orderby se.ID descending
select new ServiceSearchEntry()
{
ID = se.ID,
ServiceDateTime = se.ServiceDateTime,
Technician = u.FullName,
System = s.SystemFullName,
ReasonForFailure = se.ReasonForFailure,
RunDate = (r2 == null ? (DateTime?)null : r2.RunDate)
});
var listData = list.Skip((page - 1) * PageSize).Take(PageSize);
ServiceEntriesListViewModel viewModel = new ServiceEntriesListViewModel()
{
ServiceSearchEntry = listData,
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = list.Count()
}
};
}
The Issue:
The following clause is throwing an error when SystemFilter.System is NULL. It is null at times when users do not select values for it. Sample values are as follows:
EP1, EP2
EP1
TP2, TP3, TP4
&& ((serviceEntryFilter.System == null) || ((serviceEntryFilter.System != null) && systems.Contains(s.SystemFullName)))
If it has a value, then I put it in an array and its works like a charm, its just when its null.
The issue is that everything inside a LINQ statement will get translated to SQL. There isn't really a conditional statement that I see here that says "don't try to add this array filter if it's actually null".
I would initialize the systems array to a zero length array, overwrite it if the filter.Systems is not null, and then make my linq statement as follows:
systems.Contains(s.SystemFullName)
Don't include that null checking inside the LINQ statement as it's not doing what you are expecting.
To build conditional LINQ statements, you might want to look at PredicateBuilder: http://www.albahari.com/nutshell/predicatebuilder.aspx
This is a known limitation with Linq to Entities - see section on Referencing Non-Scalar Variables Not Supported.
In otherwords, this line:
systems.Contains(s.SystemFullName)
can't be used as part of your EF query.

Nullable Parameter used in Lambda Query is being ignored

I'm trying to pass a null value from a RenderAction to another view. But in between, at the controller, my linq lambda expression is not loading the right field, despite the null value going through correctly..
SprintManager.cshtml
<div id="Global_Backlog_Board" class="Board_Panel">
#{Html.RenderAction("ListOfSingleCards", new
{
State_ID = 1
});}
</div>
HomeController.cs
public PartialViewResult ListOfSingleCards( int? Sprint_ID,
int State_ID = 1)
{
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
return PartialView(Cards);
}
So Sprint_ID is being passed over and loaded as null here, but I can't get the query to load the rows correctly.
In fact, the following works:
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
So I suppose I could check if Sprint_ID is null and depending on the result run one of the two seperate queries, but I'd like to understand why my original attempt is not working.
Thank you!
I don't know the correct answer but based on your solution you should be able to tidy it up:
var cards = new List<Card>();
var query = db.Cards.Where(x => x.State_ID == State_ID &&
x.Deleted != 1 &&
x.Archive != 1);
if (Sprint_ID.HasValue)
query = query.Where(x => x.Sprint_ID == Sprint_ID);
else
query = query.Where(x => x.Sprint_ID == null);
cards = query.ToList();
A nullable int won't return "null" in the way that you're thinking. You have to check the HasValue property of it to determine if there is a value, and if so then use it otherwise use null:
public PartialViewResult ListOfSingleCards( int? Sprint_ID,
int State_ID = 1)
{
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID.HasValue ? Sprint_ID.Value : null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
return PartialView(Cards);
}
Until something better comes a long, I'm using this:
var Cards = new List<Card>();
if (Sprint_ID == null)
{
Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
}
else
{
Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
}

Categories