I am trying to write a query in the controller similar to what I have in my SQL stored procedure:
Select * FROM TableName Where aDate >= beginDate and aDate <= endDate
In my controller, I have declared 2 variables, which will be getting input values from my view file:
DateTime? startDate = input.BeginDateInput;
DateTime? endDate = input.EndDateInput;
and variable q that takes values from db
var q = db.tblName.AsQueryable();
Currently, I have a Select-based table of all values, looking like the following:
var data = q.Select(
p =>
new
{
//...
WarrantyExpDate = p.WarrantyExpDate.ToShortDateString(),
//...
});
When I was trying to add .Where() at the end of
Select(...).Where(DateTime.Compare(Convert.ToDateTime(WarrantyExpDate), (DateTime)startDate)>0)
(shorten for time sake), I was receiving an error WarrantyExpDate was not in the current context
. After performing some research, I tried to recreate the suggestion from that thread to swap select and where, but it was returning the same issue.
Can anyone please point me in the right direction on what I am doing wrong? How do I made both Select and Where recognize the same variable?
As BJ points out, if you're using lambda syntax, you need to provide a lambda expression to the Where method. Something like this will probably work:
var data = q
.Where(p => p.WarrantyExpDate < startDate)
.Select(
p =>
new
{
//...
WarrantyExpDate = p.WarrantyExpDate.ToShortDateString(),
//...
});
Note that I'm putting the Where
clause first. This allows you to perform the query on the original data, rather than converting it to a string and back. This is often, but not always, more desirable. Sometimes your Select does a lot of work to get a specific piece of information and you don't want to have to repeat that logic in the Where clause. The nice thing about LINQ is that you get to choose what's easiest.
You might also consider using Query syntax instead; it ends up compiling down to pretty much the same thing, but it looks a little nicer when you've got big queries.
var data =
from p in q
where p.WarrantyExpDate < startDate
select new
{
//...
WarrantyExpDate = p.WarrantyExpDate.ToShortDateString(),
//...
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With