I have the following code which declares two variables and then executes a query. The variables will be created no matter what, so I am surprised to be getting an object does not exist in current context error when the query is about to execute. How can I do something like this? It has happened several times. I also tries to use an if/else statement in the declaration of the variable but that has not worked. (Then I get the error invalid expression if) What do I need to say for this to work?
if (from_date == null) {
var from_date_choose = DateTime.Today.AddDays(-30);
} else {
var from_date_choose = from_date;
}
if (to_date == null) {
var to_date_choose = DateTime.Today;
} else {
var to_date_choose = to_date;
}
var voyages = db.Voyages
.Where(v => v.ArrivalDatetime >= from_date_choose)
.Where(v => v.ArrivalDatetime <= to_date_choose);
Modify the code like this, otherwise your variables exist only in local scope. You also need to use from_date.Value and to_date.Value (I assume these are of type Nullable<DateTime>):
DateTime from_date_choose;
if (from_date == null) {
from_date_choose = DateTime.Today.AddDays(-30);
} else {
from_date_choose = from_date.Value;
}
DateTime to_date_choose;
if (to_date == null) {
to_date_choose = DateTime.Today;
} else {
to_date_choose = to_date.Value;
}
var voyages = db.Voyages
.Where(v => v.ArrivalDatetime >= from_date_choose)
.Where(v => v.ArrivalDatetime <= to_date_choose);
You may also use the ternary operator, eg.:
DateTime from_date_choose = from_date == null ? DateTime.Today.AddDays(-30) : from_date.Value;
Or as Jeppe Stig Nielsen suggested use coalesce operator, eg:
DateTime from_date_choose = from_date ?? DateTime.Today.AddDays(-30);
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