I have a simple LINQ query. I would like to only check the DateDisable if there is an entry in the database. If the user doesn’t select a date to disable the entry will always show. Can someone please show me how to add a conditional statement within linq
return (from promo in context.Promoes
where promo.DateEnable <= DateTime.Today
where promo.DateDisable >= DateTime.Today
orderby promo.SortOrder
select promo).ToList();
Given that
DateEnableis aDateTime?, you can do the following:Basically, you need to check for
nullor whether or not the date is greater than today.Also you should capture the value outside of the statement, it’s not guaranteed that the the LINQ provider will translate
DateTime.Todayon the database side correctly.However, be warned that because of deferred execution, if you wait a long time to execute the query,
todaymight not give you the value you expect (if the time between declaring the query and executing it rolls past midnight).Of course, if your database server is in a different timezone than your application server, then you’ll need to ensure that
DateTime.Todayis handled by your LINQ provider correctly (so that it’s executed on the server) and use that if you want to compare against time on the DB server. If your provider doesn’t handle translatingDateTime.Todaycorrectly, then you’ll have to resort to a stored procedure and call that.