I have a Linq query that works with various Where clause additions.
But I also want to return the SingleDate for an Event where it is today or tomorrow.
Dances_Moderated = Dances_Moderated
.Where(x => x.SingleDate == DateTime.Today)
&& (x => x.SingleDate == DateTime.Today.AddDays(1))
.ToList();
The code after the && is underlined in red, and the error says:
CS0023: Operator '.' cannot be applied to operand of type 'lambda expression'
You should use || (or) instead of && (and): x.SingleDate.Date should be either Today or tomorrow. I've added .Date in order to be on the safe side of the road: when we use == we want to compare dates only, not time parts.
Dances_Moderated = Dances_Moderated
.Where(x => x.SingleDate.Date == DateTime.Today ||
x.SingleDate.Date == DateTime.Today.AddDays(1))
.ToList();
You have couple of errors in your code:
First: Syntax error,
Second: Business error. Your SingleDate never gonna equal to datetime.now. You should use greater and less operator to do that.
Your code should be like this:
Dances_Moderated = Dances_Moderated.Where(x => x.SingleDate >= DateTime.Today && x.SingleDate <= DateTime.Today.AddDays(1)).ToList();
Related
OK, this doesn't work due to Azure Table query subset constraints:
var res = tcmarketnlog.Where(t => t.Level == level && t.Message.Contains("151207151510") && t.Timestamp >= start && t.Timestamp <= end).Take(1000);
The t.Message.Contains("151207151510") bombs. However, there must be some way to then search the results in LINQpad and select only the results with this string in the message.
For example, I could not coerce the result into a variable that was then queriable again with LINQ. Any tips?
If you can't use string.Contains on an Azure Table Queryable, you can still turn it into an Enumerable and then apply the additional filter to only show the results you want. However, it means that it will return all records that meet the other criteria over the network before then limiting them on the client side to only those rows where the Message field contains the specified string.
var res = tcmarketnlog.Where(t => t.Level == level && t.Timestamp >= start && t.Timestamp <= end).AsEnumerable().Where(t => t.Message.Contains("151207151510")).Take(1000);
Maybe message is null. Just check message null before contains. pls try this:
var res = tcmarketnlog.Where(t => t.Level == level
&& t.Message != null && t.Message.Contains("151207151510")
&& t.Timestamp >= start && t.Timestamp <= end).Take(1000);
I've got some IQueryables I would like to OR together. My understanding is chaining them together using Where results in ANDing them together (though my understanding may be faulty.)
Here's an example of a query I would like to OR together, in lieu of using all the chained Where clauses:
var query = query.Where(x => x.Value == 1)
.Where(x => x.Name == name);
Instead of that, I'm looking for something like:
var query = query.Where(x => x.Value == 1)
.Or(x => x.Name == name)
.Or(x => x.SomeOtherValue == something else)
.Or(x => x.AChildObject.Items.Where(item => item.SomeValue == yet something else));
...in my case there are probably 10 or items I'd need to chain together like above.
I've been looking over posts like this one and I suppose I could use a series of || statements to chain things together, but am not sure if that's the way to go. It could get very hard to read.
In researching this online I'm running into meaty articles on PredicateBuilders and the like. I'm not an expert on LINQ by any means and I was hoping for some guidance?
It looks like that you can just use OR operator.
var query = query.Where(x => x.Value == 1
|| x.Name == name)
|| x => x.SomeOtherValue == something else)
|| x => x.AChildObject.Items.Where(item => item.SomeValue == yet something else))
You can also use Union or Concat if the data being combined from different sources, see Linq union usage?
I am building a query tool for use by non technical staff to retrieve records from the database.
I have a form with various drop downs which can be selected by the user depending on what they are looking for.
I have come across a problem where my query is returning records that do not match the users selection.
I believe this is only happening when I am querying the joined tables.
I have the following:
results = results.Where(c => c.CustomerEnrollment
.Where(x => x.CustomerCategoryID == CustomerCategoryID)
.Any());
results = results.Where(c => c.CustomerEnrollment
.Where(x => x.StartDate <= DateRangeStart && x.EndDate >= DateRangeStart)
.Any());
This will return results for the correct category but not within the specified date range.
I have also tried:
results = results.Where(c => c.CustomerEnrollment
.Any(x => x.CustomerCategoryID == CustomerCategoryID));
Try changing your date range check as;
Change:
x => x.StartDate <= DateRangeStart && x.EndDate >= DateRangeStart
To:
//StartDate should be greater than or equal to
//EndDate should be less than or equal to
//Also you are using same variable DateRangeStart to check start and end
x => x.StartDate >= DateRangeStart && x.EndDate <= DateRangeEnd
Your query returns categories that have any CustomerEnrollment having their Id, and also have any CustomerEnrollment in the the required data range, but these CustomerEnrollments are not necessarily the same.
To make sure that you get categories with CustomerEnrollments that fulfill both conditions you have to do:
results = results.Where(c => c.CustomerEnrollment
.Where(x => x.CustomerCategoryID == CustomerCategoryID
&& x.StartDate <= DateRangeStart
&& x.EndDate >= DateRangeStart)
.Any());
With PredicateBuilder you can parametrize the conditions:
using LinqKit;
...
var pred = Predicate.True<CustomerEnrollment>();
if (CustomerCategoryID > 0)
pred = pred.And(c => c.CustomerCategoryID == CustomerCategoryID);
if (DateRangeStart.HasValue)
pred = pred.And(c => c.StartDate <= DateRangeStart
&& c.EndDate >= DateRangeStart);
results = results.AsExpandable()
.Where(c => c.CustomerEnrollment.AsQueryable()
.Any(pred));
The combination of .AsExpandable() and .AsQueryable() appears to be the only way to avoid exceptions.
I need to compare just the date only in a Linq query that involves a datetime field. However, the syntax below results in the following error message
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Does anyone know how to extract just the date out of a datetime field?
var duplicate = from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
a.DateTaken.Date == course.DateTaken.Date &&
a.SymNumber == symNumber
select a;
It might seem a little roundabout, but you can use the SqlFunctions class' DateDiff method for doing this. Just pass in both values and use "Day" for finding the difference between them in days (which should be 0 if they are on the same day).
Like the following:
from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
SqlFunctions.DateDiff("DAY", a.DateTaken, course.DateTaken) == 0 &&
a.SymNumber == symNumber
select a;
You can use EntityFunctions.TruncateTime() under the namespace System.Data.Objects
Ex.
db.Orders.Where(i => EntityFunctions.TruncateTime(i.OrderFinishDate) == EntityFunctions.TruncateTime(dtBillDate) && i.Status == "B")
Works like charm.
UPDATE
This function works only when you querying entities through LINQ. Do not use in LINQ-Object.
For EF6 use DbFunctions.TruncateTime() under System.Data.Entity namespace.
You can do it like bellow:
var data1 = context.t_quoted_value.Where(x => x.region_name == "Pakistan"
&& x.price_date.Value.Year == dt.Year
&& x.price_date.Value.Month == dt.Month
&& x.price_date.Value.Day == dt.Day).ToList();
you must use System.Data.Entity.DbFunctions.TruncateTime
try this
DateTime dt =course.DateTaken.Date;
var duplicate = from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
a.DateTaken == dt &&
a.SymNumber == symNumber
select a;
if a.DateTaken contains Time also, then refer these links to modify your date.
The Date property cannot be used in LINQ To Entities.
Compare Dates using LINQ to Entities (Entity Framework)
'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported
http://forums.asp.net/t/1793337.aspx/1
This is how I ended by doing a similar Date search which I had to consider time (Hour and Minutes portion) also
from x in _db.AgentProductTraining
where
x.CreatedOn.Year == mydacourse.DateTakente.Year
&& x.CreatedOn.Month == course.DateTaken.Month
&& x.CreatedOn.Day == course.DateTaken.Day
&& x.CreatedOn.Hour == course.DateTaken.Hour
&& x.CreatedOn.Minute == course.DateTaken.Minute
select x;
Hey when I was building a query this below worked
DateTime date = Convert.ToDateTime(SearchText);
query = query.Where(x => x.Date.Month == date.Month
&& x.Date.Day == date.Day
&& x.Date.Year == date.Year);
// Let me know if this worked for you as it pulled the date that was searched for me
Take off the .Date
If the field is a DateTime it can be compared with ==
var duplicate = from a in _db.AgentProductTraining
where a.CourseCode == course.CourseCode &&
a.DateTaken == course.DateTaken &&
a.SymNumber == symNumber
select a;
Iām trying to retrieve data from an entity and populate a viewModel property like this:
viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday") && (db.Enrollments.Where(b => b.CourseID == courseID);
but I get a operator && cannot be applied to operands of type System.Linq.IQerable<> error. Can you help with a way to find all Monday class with the same ID?
I tried this: viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday") but I get all Mondays courses but I want to limit them to a specific courseID.
Please help!
You need to examine your parentheses. This code won't even compile:
viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday")
&& (db.Enrollments.Where(b => b.CourseID == courseID);
In that code you're trying to use && between two calls to .Where(), which return an IQueryable. You probably mean to use && within the .Where() clause:
viewModel.Enrollments = db.Enrollments.Where(b => (b.classDays == "Monday")
&& (b.CourseID == courseID));
Or perhaps append a second .Where() clause:
viewModel.Enrollments = db.Enrollments.Where(b => b.classDays == "Monday")
.Where(b => b.CourseID == courseID);
Note that .Where() can be chained indefinitely, essentially resulting in applying each clause in turn in an AND fashion in the resulting query.
&& Operator should be used with conditions inside where NOT with sets of enrollments (in your case)
Try This:
viewModel.Enrollments = db.Enrollments.Where(b => (b.classDays == "Monday") && (b.CourseID == courseID));