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)
Related
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.
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();
I am getting an unusual "NullReferenceException was unhandled by user code" error in this LINQ query:
List<UDIDInfo> d2Android = d2.Where(x.DeviceOS == (byte)DeviceOS.Android).ToList();
I went ahead and added a null check and am still getting the error
List<UDIDInfo> d2Android = d2.Where(x => x.DeviceOS != null && x.DeviceOS == (byte)DeviceOS.Android).ToList();
Note that (byte)DeviceOS.Android and d2 are both not null
Edit (Solution):
List<UDIDInfo> d2Android = d2.Where(x => x != null && x.DeviceOS != null && x.DeviceOS == (byte)DeviceOS.Android).ToList();
What if x is null? That is, the enumerable d2 contains a null item.
Try the following. You shouldn't get any null reference exception.
List<UDIDInfo> d2Android = d2
.Where(x => x != null)
.Where(x => x.DeviceOS != null)
.Where(x => x.DeviceOS == (byte)DeviceOS.Android)
.ToList();
avoid the argument null exception in LINQ like below
Summaries = (from r in Summaries
where r.Contains(SearchTerm)
orderby r
select r).ToArray();
In this case, if null passed to searchTerm you can check the null expression like below
Summaries = (from r in Summaries
where string.IsNullOrEmpty(SearchTerm) ||r.Contains(SearchTerm)
orderby r
select r).ToArray();
To one of my tables I added a sortOrder. I now need to update this query to respect the sortOrder authority!
Here is my current query:
var HTMLdocs = db.ProcedureDocs.Where(m => m.Procedures.Processes.processID == id && m.Document.html != null && m.Document.approvedBy != null).Select(m => m.Document);
The table that has sortOrder is Procedures.
How can I get the above query to return results that are ordered by sortOrder.
Here is the table structure.
Processes can have 0 or many Procedures.
Document can have 0 or many ProcedureDocs.
ProcedureDocs has a foreign key to Procedures on procedureid.
I somehow need to grab a collection of Document that somehow respects the order found in the Procedures table.
Let me know if you need any other information.
Try something like this:
var HTMLdocs = db.ProcedureDocs
.Where(m => m.Procedures.Processes.processID == id &&
m.Document.html != null &&
m.Document.approvedBy != null)
.OrderBy(m => m.Procedures.sortOrder)
.Select(m => m.Document);
Or in query syntax:
var HTMLdocs =
from m in db.ProcedureDocs
where m.Procedures.Processes.processID == id &&
m.Document.html != null &&
m.Document.approvedBy != null
orderby m.Procedures.sortOrder
select m.Document;
var HTMLdocs = db.ProcedureDocs
.Where(m => m.Procedures.Processes.processID == id
&& m.Document.html != null && m.Document.approvedBy != null)
.OrderBy(x=>x.Procedures.sortOrder)
.Select(m => m.Document)
This has caused me no end of problems today. I have this simple query
var result =
DataContext.Accommodations.Where(a =>
(criteria.MinPrice == null || a.AccommodationRates.Any(r => r.From >= criteria.MinPrice)) &&
(criteria.MaxPrice == null || a.AccommodationRates.Any(r => r.To <= criteria.MaxPrice)) &&
(criteria.Locations == null || criteria.Locations.Count == 0 || a.AccommodationPlaceJoins.Any(j => criteria.Locations.Contains(j.Place.PlaceName)))
);
The last line of this query is causing me problems
(criteria.Locations == null ||
criteria.Locations.Count == 0 ||
a.AccommodationPlaceJoins.Any(j => criteria.Locations.Contains(j.Place.PlaceName)))
The error it gives is
Unable to create a constant value of type
'System.Collections.Generic.IList`1'. Only primitive types ('such as
Int32, String, and Guid') are supported in this context.
I'm not even trying to create a list. All I'm trying to do here is bring back accommodations which are associated to a place (where the place name in the Place table which is linked to the Accommodation table via the AccommodationPlaceJoin table) is equal to any one of the place names in criteria.Locations (which is of type IList).
I've tried changing this line to this, but it didn't work.
(criteria.Locations == null ||
criteria.Locations.Count == 0 ||
a.AccommodationPlaceJoins.Any(j => criteria.Locations.Any(l => l == j.Place.PlaceName)))
The constant value EF can't create is null for the comparison criteria.Locations == null. You need to split the query into two cases and do the check for the empty list outside of the query, for example like so:
var result = DataContext.Accommodations.Where(a =>
(criteria.MinPrice == null ||
a.AccommodationRates.Any(r => r.From >= criteria.MinPrice)) &&
(criteria.MaxPrice == null ||
a.AccommodationRates.Any(r => r.To <= criteria.MaxPrice)));
if (criteria.Locations != null && criteria.Locations.Count > 0)
{
result = result.Where(a => a.AccommodationPlaceJoins
.Any(j => criteria.Locations.Contains(j.Place.PlaceName)));
}
Edit
BTW: Composing the whole query would make it better readable in my opinion and will simplify the SQL that has to be sent to the database:
IQueryable<Accommodation> result = DataContext.Accommodations;
if (criteria.MinPrice != null)
result = result.Where(a => a.AccommodationRates
.Any(r => r.From >= criteria.MinPrice));
if (criteria.MaxPrice != null)
result = result.Where(a => a.AccommodationRates
.Any(r => r.To <= criteria.MaxPrice));
if (criteria.Locations != null && criteria.Locations.Count > 0)
result = result.Where(a => a.AccommodationPlaceJoins
.Any(j => criteria.Locations.Contains(j.Place.PlaceName)));
I had this same issue when trying to pass a list of strings for comparison into an EF core query recently and found that it resolves the issue to assign an empty array or empty list to the value in case it is null rather than doing the null check right in the EF Core query.
This allows you to query the EF Core database without the null error and you don't need a bunch of conditional branching for separate queries - just one query with a bit of null coalescence.
So your code fixed this way would look like this:
var locations = criteria.Locations == null ? new List<Location>() : criteria.Locations;
var result =
DataContext.Accommodations.Where(a =>
(criteria.MinPrice == null || a.AccommodationRates.Any(r => r.From >= criteria.MinPrice)) &&
(criteria.MaxPrice == null || a.AccommodationRates.Any(r => r.To <= criteria.MaxPrice)) &&
(locations.Any() ? a.AccommodationPlaceJoins.Any(j => criteria.Locations.Contains(j.Place.PlaceName))) : true);
Keep in mind I am not sure of the type for locations or accomodationplacejoins so I cannot be sure the above code will exactly work but the general idea is we are doing a .Any() instead of checking for null. This way we can keep our query a little simpler. We are then using a ternary expression within the last block of our where clause so if the locations list turns out to be empty, we skip the condition entirely and just return true which coalesces the empty list if it is empty.