EF Core with '&&' and '||' inside lambda expression - c#

The following query is not returning the proper results, it will return properly for company, but not the other two parameters. For clarification this is inside a post method of a page taking the user's input for company, name, and/or state
var transporters = await _db.TransporterProfiles
.Include(x => x.TransportState)
.Where(x => x.Company == company || company == null &&
x => x.LastName == name || name == null &&
x => x.TransportState.Name == state || state == null)
.ToListAsync();
I've tried adding parentheses around each part of the query such as
.Where((x => x.Company == company || company == null) &&
(x => x.LastName == name || name == null) &&
(x => x.TransportState.Name == state || state == null))
but this produces an error
Operator '&&' cannot be applied to operands of type 'lambda expression'

There's no reason to include company == null in the query. If you don't want a search term, don't include it at all. You can build AND conditions by adding Where clauses to a query as needed, eg :
if(value1 != null)
{
query=query.Where(x=>x.Property1 == value1);
}
if(value2 != null)
{
query=query.Where(x=>x.Property2 == value2);
}
In the question's case you can write something like this:
var query=_db.TransporterProfiles.Include(x => x.TransportState).AsQueryable();
if(company!=null)
{
query=query.Where(x => x.Company == company);
}
if(name!=null)
{
query=query.Where(x => x.LastName == name);
}
if(state!=null)
{
query=query.Where(x => x.TransportState.Name == state);
}
var transporters=await query.ToListAsync();
You don't need to include TransportState to use x.TransportState.Name in the Where clause. Include is used to eagerly load related data, not tell EF to JOIN between related tables.
If you don't want Include you can start the query with :
var query=_db.TransporterProfiles.AsQueryable();

The issue with your syntax is you have multiple lambdas that should be one.
.Where(x => (x.Company == company || company == null) &&
(x.LastName == name || name == null) &&
(x.TransportState.Name == state || state == null))
That said the actual solution is to do what #PanagiotisKanavos posted as an answer, generate the query dynamically based on the input values.

Related

Simplify LINQ query

I have the following query:
db.ObjectTags.Where(c =>
c.TagID == tagID &&
(!db.DeletedObjects.Any(d=> d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID)
|| !db.DeletedObjects.SingleOrDefault(d => d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID).Deleted)
)
Its goal is to return objects that are not in a deleted state.
The table DeletedObjects has two states:
A record doesn't exist (not deleted)
A record exists with a deleted (bool) value
I need to query where either the record doesn't exist, or if it does the deleted value is false.
Is there any way to condense that statement eg with SingleOrDefault()?
You only need one !db.DeletedObjects.Any(...) and no SingleOrDefault
var q = db.ObjectTags
.Where(c=> c.TagID == tagID && !db.DeletedObjects
.Any(d => d.Deleted && d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID));
Can you please try this linq query
db.ObjectTags.Where(c =>
c.TagID == tagID &&
(db.DeletedObjects.Any(d=> d.ForObjectTypeID == c.ForObjectTypeID && d.ForObjectID == c.ForObjectID && !c.Deleted))
)
I believe you need to left join between ObjectTags and DeletedObjects. A LINQ query like this:
from objectTag in db.ObjectTags
from deletedObject in db.DeletedObjects
.Where(deletedObject => deletedObject.ForObjectTypeID == objectTag.ForObjectTypeID && deletedObject.ForObjectID == objectTag.ForObjectID)
.DefaultIfEmpty()
where deletedObject == null || !deletedObject.Deleted

Optimize EF query using Any instead of contains

That was my query with Contains:
db.NavFilters.Where(finalExpression)
.Count(x => x.Attribute1 == e.Attribute && x.Link == link && x.SubLink == subLink && db.NavItemsFilters
.Where(n=> !(n.Promo == string.Empty || n.Promo == null))
.Select(n=>n.ItemID)
.Contains(x.ItemID) )
But, as far as I know, contains is a hard operation, and I need to optimize it. Is such query will give the same result?
db.NavFilters.Where(x=> db.NavItemsFilters.Any(n=>n.Promo != string.Empty && n.ItemID == x.ItemID))
.Where(finalExpression)
.Count(x => x.Attribute1 == e.Attribute && x.Link == link && x.SubLink == subLink)
I know, that the best solution is to add navigation properties. But I can't do that for many reasons.
You can optimize you query like this:
var navFilters = db.NavFilters.Where(finalExpression);
var thereIsAny = (from x in navFilters
join n in db.NavItemsFilters on x.ItemID equals n.ItemID
where n.Promo != string.Empty && x.Attribute1 == e.Attribute && x.Link == link && x.SubLink == subLink
).Any();
IQueryable.Contains does exist, so your query should get converted to SQL.

Rewrite sql query to LINQ. Can't find an error

This is an SQL query:
SELECT Website,VendorID,Name,LinkProduct,
Link,Logo,Image,NameExtra as Industry,
(SELECT [Percent] FROM Web_Promotion
WHERE Web_Promotion.VendorID=Web_Vendor.VendorID)
AS PercentOff
FROM Web_Vendor WHERE Active='1' AND
(VendorID IN (Select VendorID FROM Web_Promotion
WHERE VendorID<>'' AND Static='True' AND [Percent] <> '0' AND
((Expires>=GETDATE()) OR (Expires IS NULL))) OR
VendorID IN (SELECT TOP 1 SC1 FROM NavItems
WHERE SC1=Web_Vendor.VendorID AND Promotion<>''
AND ((PromotionStart<=GETDATE() AND PromotionEnd>=GETDATE())
OR (PromotionStart<=GETDATE() AND PromotionEnd IS NULL))))
ORDER BY NameExtra,Sequence
I need to rewrite it to LINQ. So this is my LINQ:
return await _db.Web_Vendor.
Where(x => !(x.WebPromotion.VendorID == string.Empty || x.WebPromotion.VendorID == null)
&& x.WebPromotion.Static == true && x.WebPromotion.Percent != 0 &&
(x.WebPromotion.Expires >= DateTime.Now || x.WebPromotion.Expires == null)
||
(_db.NavItems.Where(y => x.WebPromotion.VendorID == y.SC1
&& !(y.Promotion == "" || y.Promotion == null)
&& (y.PromotionStart <= DateTime.Now) && (y.PromotionEnd >= DateTime.Now || y.PromotionEnd == null))
.Select(g => g.SC1).Take(1).Contains(x.WebPromotion.VendorID)))
.Include(x => x.WebPromotion).Where(x => x.Active == true).OrderBy(x => x.NameExtra)
.ThenBy(x => x.Sequence).ToListAsync();
I spent about three ours, but can't find an error. Original SQL query returns 16 rows, but my LINQ code returns only 13 of the. Unfortunately I have only one navigation property (Web_Vendor <-> Web_Promotion). I think that an error in the second part of my query:
||
(_db.NavItems.Where(y => x.WebPromotion.VendorID == y.SC1
&& !(y.Promotion == "" || y.Promotion == null)
&& (y.PromotionStart <= DateTime.Now) && (y.PromotionEnd >= DateTime.Now || y.PromotionEnd == null))
.Select(g => g.SC1).Take(1).Contains(x.WebPromotion.VendorID)))
Can any expert check my code and help me?
Correct data:
http://prntscr.com/9a5xwu
Linq data (not correct) contains the same data as correct instead of values where PercentOff is null.
The main problem is that LINQ generate inner join instead of left join in this place: http://prntscr.com/9a6stb
since you say that your linq data miss the case when PercentOff = null, i'd focus on that
I guess your "PercentOff" in Linq is Percent property, and i see that you have in your where: "x.WebPromotion.Percent != 0"
Is that a nullable value or you convert the null to the default property type, that is 0?
couldn't be that null is converted to 0 and then the query skip it?

filtering results with Entity Framework

another kinda newbie question I guess. I have EF setup and now I want to select some records based on a filter. I have SomeClass with 4 items (all strings to keep things simple, lets call them string1, string2, and so on). Now, in a post I send the filter in an instance of SomeClass, but maybe not all properties are filled in.
So you might end up with string1="something", string2="bla" and string4="bla2". So string 3 = null. Now, how do I setup the query? If i try something like:
var dataset = entities.mydatabase
.Where(x => x.string1 == someclass.string1 && x.string2 == someclass.string2 && x.string3 == someclass.string3 && x.string4 == someclass.string4)
.Select(x => new { x.string1, x.string2, x.string3, x.string4}).ToList();
... I get no results, because string3=null. I could do something with checking all parameters and see if they're set and create the query based on that, but there must be something more elegant than that.
Anyone?
Thanks!
Ronald
The following will return all rows where the someclass.string is null OR equals to x.string.
var dataset = entities.mydatabase
.Where(x => someclass.string1 == null || x.string1 == someclass.string1)
.Where(x => someclass.string2 == null || x.string2 == someclass.string2)
.Where(x => someclass.string3 == null || x.string3 == someclass.string3)
.Where(x => someclass.string4 == null || x.string4 == someclass.string4)
.Select(x => new { x.string1, x.string2, x.string3, x.string4}).ToList();

how to debug `Null reference exception occured` in linq?

string search = textBoxNachname.Text;
var Liste = _db.T_Subscribers
.Where(x => x.firstname.StartsWith(search))
.Except(_selectedcourse.T_Coursedetail.Select(b => b.T_Subscribers))
.Where(M => M.T_Tln_Student == null || M.T_Tln_Stud.Status.T_Status.T_Statusart == _studentEx).ToList();
I have written the above piece of code to extract a list whose name starts with the Search element in textbox...then I need to exclude the names who have already enrolled for the course, then if they are not the students of the Institution (M => M.T_Tln_Student == null) and ex-students include in the list..
But I am getting Null reference exception occurred...
This is how you can debug this:
var Liste1 = _db.T_Subscribers.Where(x => x.firstname.StartsWith(search));
var Liste2 = Liste1.Except(
_selectedcourse.T_Coursedetail.Select(b => b.T_Subscribers));
var Liste3 = Liste2.Where(M =>
M.T_Tln_Student == null ||
M.T_Tln_Stud.Status.T_Status.T_Statusart == _studentEx);
var Liste = Liste3.ToList();
The focus is to use this technique to split things.
look at this line:
.Where(M => M.T_Tln_Student == null ||
M.T_Tln_Stud // might be null
.Status // might be null
.T_Status // might be null
.T_Statusart // might be null
== _studentEx)
I would suggest that you start your search for the NullReferenceException here
.Where(M => M.T_Tln_Student == null ||
M.T_Tln_Stud == null ||
M.T_Tln_Stud.Status == null||
M.T_Tln_Stud.Status.T_Status == null ||
M.T_Tln_Stud.Status.T_Status.T_Statusart == null ||
M.T_Tln_Stud.Status.T_Status.T_Statusart == _studentEx)

Categories

Resources