I have a field with datatype numeric and I have stored hour values in it. Now I want to subtract the hours of a DateTime field with the numeric field and compare it with DateTime.Now() in a where clause of LINQ query. i'm using this logic `private List GetInterviewExamSlots(int programPreferenceId, string lookuptype)
{
var currentDateTime = DateTime.UtcNow;
var schedules = uow.RepositoryAsync<CoC_Schedule_Entry>()
.Queryable()
.AsNoTracking()
.OrderByDescending(x=> x.Start_Datetime)
.Where(x => x.Capacity != null &&
x.Capacity != 0 &&
(x.Start_Datetime).AddHours((double)- x.Event_Registration_Deadline) > currentDateTime &&
x.Fully_Booked_Flag != Constants.YesFlag &&
x.CoC_Schedule_Entry_Type.Schedule_Entry_Type_Code.Equals(lookuptype) &&
x.CoC_Lookup3.Hidden_Value.Equals(LookupCodes.OpenHiddenValue)
&& (x.Program_Preference_ID == programPreferenceId
||
x.Program_Preference_ID == null))
.Select(x => new ............`
but it throws an exception LINQ to Entities does not recognize the method '.AddHours' method and this method cannot be translated into a store expression.
Not everything, that can be expressed in C# can be translated to the store's language. What this is, depends on the specific store and the LINQ provider (like e. g. entity framework for sqlserver). In your case the provider can't translate the AddHours function call.
To get past this you can
remove the method call from your query, convert the result to something that can be queried via Linq2Objects (e. g. by adding .ToList() to convert your (intermediate) result to a List<...>) and then query it again. Now that nothing needs to be translated, AddHours (and any other function call) will work.
Depending on your data this might consume many local resources.
var preSelectedSchedules = uow.RepositoryAsync<CoC_Schedule_Entry>()
.Queryable()
.AsNoTracking()
.OrderByDescending(x=> x.Start_Datetime)
.Where(x => x.Capacity != 0
&& x.Fully_Booked_Flag != Constants.YesFlag
&& x.CoC_Schedule_Entry_Type.Schedule_Entry_Type_Code.Equals(lookuptype)
&& x.CoC_Lookup3.Hidden_Value.Equals(LookupCodes.OpenHiddenValue)
&& (x.Program_Preference_ID == programPreferenceId
|| x.Program_Preference_ID == null))
.ToList();
var schedules = preSelectedSchedules
.Where(x => x.Start_Datetime.AddHours(-x.Event_Registration_Deadline) > currentDateTime)
.Select(...);
provide a query in the store's language (like a view if we're talking about sql) which returns the desired data and you use this a the data source of your query.
If you have very few different values for x.Event_Registration_Deadline, you can also try another approach:
select all distinct values for x.Event_Registration_Deadline
for each value calculate var theshold = currentDateTime.AddHours(<value>);
perform the query with .Where(x => x.Start_Datetime > threshold)
Related
I am trying to get a list with some data from SQL using Linq. The results in list are based on date which the user inputs.
My code for getting the list
TimologioList = Dao.SearchTimologiaNotSendToMydata(apoDateEdit.DateTime,
eosDateEdit.DateTime.Date.AddDays(1).AddMilliseconds(-1),
MainDoc.Xrisi,
DefaultDiasafistis.DiasafistisDefault,
apestalmenaCheckEdit.Checked);
public List<Timologio> SearchTimologiaNotSendToMydata(DateTime apoDate, DateTime eosDate, string xrisi, Diasafistis diasafistis, bool apestalmenaTimologia)
{
List<Timologio> timologia = db.Timologio
.Where(p => (p.Imerominia >= apoDate && p.Imerominia <= eosDate)
&& (p.Xrisi == xrisi && p.Diasafistis == diasafistis)
&& (!p.IsYpodeigma.HasValue || !p.IsYpodeigma.Value)
&& p.ArithmosTimologiou != 0)
.OrderByDescending(p => p.Imerominia).ToList();
return timologia;
}
The two variables have values apoDate = 1/1/2022 12:00:00 and eosdate = 31/1/2022 11:59:59.
When I run this query, it returns another result which has a date of 1/2/2022 and I don't understand why.
Values of the date variables:
SQL data:
Results in the program:
I am using DateTime.Date.AddDays(1).AddMilliseconds(-1) because I found that it gives more precise values in the date
var tmp = productDBSet.Where(x => x.lastUpdate >= DateTime.MinValue && x.lastUpdate.Value.ToString("MM/yyyy") == curMonth).Select(x => x.ID);
While I run above code, I got this error message:
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated
into a store expression.
Also I tried,
var tmp = productDBSet.Where(x => x.lastUpdate >= DateTime.MinValue && x.lastUpdate.Value.ToString("MM/yyyy") == curMonth).ToList().Select(x => x.ID);
But same,
How can I solve that?
As the error message is telling you, the ToString method of DateTime isn't supported.
Since you're just trying to determine if the month and year of the date match a given value, you can just compare the actual month and year, rather than trying to get a string containing the month and year that you compare with.
x.lastUpdate.Value.Year == yearToCompareWith &&
x.lastUpdate.Value.Month = monthToCompareWith
You cannot use ToString() in Linq to Entities. Try something like this (I've assumed that x.lastUpdate is of type "DateTime"):
x.lastUpdate.Month == curMonth && x.lastUpdate.Year == curYear
This happens, because LINQ to Entities is translated to SQL queries, and therefore method ToString is not recognised.
You can not use extension methods in linq queries, since these are unable to get converted to equivalent Sql Queries. You can use following linq:
var tmp = productDBSet.Where(x => x.lastUpdate >= DateTime.MinValue && x.lastUpdate.Month == curMonth && x.lastUpdate.Year == curYear).Select(x => x.ID);
My application is running under ASP.NET 4.0, which uses BLToolkti as ORM tool.
I have some queryable expression:
var q = db.GetTable<T>()
.Where(tb=>tb.TeamId==MyTeamId && tb.Season==MySeasonId)
.OrderByDescending(tb=>tb.Id)
.Take(20)
.Reverse()
Attempt to convert q.ToList() causes the following error:
Sequence 'Table(TeamBudget).Where(tb => ((tb.TeamId ==
value(VfmElita.DataLogicLayer.Teams.Team+TeamBudget+<>c__DisplayClass78).teamId)
AndAlso (tb.Season ==
value(VfmElita.DataLogicLayer.Teams.Team+TeamBudget+<>c__DisplayClass78).season))).OrderByDescending(tb
=> Convert(tb.Id)).Take(20).Reverse()' cannot be converted to SQL.
If I remove ".Reverse()" from the queryable object everything works fine.
What is the reason why queryable object with .Reverse() cannot be converted into SQL? Is that BLToolkit limitation? Is there any solution workaround for that?
Thank you!
It's pretty clear what the other LINQ methods convert to (where, order by, top(20)), but what would Reverse() convert to? I can't think of an SQL statement I've seen that mimics that behavior, and when you're querying the database your LINQ statement must ultimately resolve to valid SQL.
This may not be what you're going for, but one option would be to execute the query first using ToList(), then apply Reverse():
var q = db.GetTable<T>()
.Where(tb => tb.TeamId == MyTeamId && tb.Season == MySeasonId)
.OrderByDescending(tb => tb.Id)
.Take(20)
.ToList()
.Reverse();
Alternatively, you could get the count and skip that many records first, although this could be inaccurate if the number of records change between calls. Plus it's two queries instead of just one.
var totalRecords = db.GetTable<T>()
.Count(tb => tb.TeamId == MyTeamId && tb.Season == MySeasonId);
var q = db.GetTable<T>()
.Where(tb => tb.TeamId == MyTeamId && tb.Season == MySeasonId)
.Order(tb => tb.Id)
.Skip(totalRecords)
.Take(20);
Is it possible within Linq in C#, to convert a string field in a database, to a long type - and use it in the query?
Here, tme is a unix time (long) - but the field in the database, targetdate - is a string.
I've tried:
var qbt = db.Calls
.Where(x => x.team == id && long.Parse(x.targetdate) <= tme);
However I get the message: LINQ to Entities does not recognize the method 'Int64 Parse(System.String)' method, and this method cannot be translated into a store expression.
I know you can convert before the linq query, but is there any way of using it WITHIN the linq query?
Thanks for any help,
Mark
try
var qbt = db.Calls.ToList()
.Where(x => x.team == id && long.Parse(x.targetdate) <= tme);
if you have many records you can limit them by team first and then call ToList like below
var qbt = db.Calls.Where(x => x.team == id).ToList()
.Where(i=>long.Parse(i.targetdate) <= tme);
Or You can use AsEnumerable
var qbt = db.Calls.AsEnumerable()
.Where(x => x.team == id && long.Parse(x.targetdate) <= tme);
This is to do with the way the Linq is translated into the backing query language, it might be easier to do a string comparison in this case, using tme.ToString(). If you pull the full collection down first, you could query like this but that means what it says: pulling down the full unfiltered (or at least less filtered) set.
You have to either change the database table to not store a string (you could create a computed column that converts it to a long or create a view if you cannot modify the existing table) or compare the value as string. The reason is that Entity Framework LINQ provider does not understand long.Parse and there is no method in SqlFunctions class for this purpose.
var stringTme = tme.ToString(CultureInfo.InvariantCulture);
var qbt = db.Calls
.Where(x => x.team == id && ((x.targetdate.Length < stringTme.Length)
|| (x.targetdate.Length == stringTme.Length && x.targetdate <= stringTme)));
You have to either change the database table to not store a string or compare the value as string. The reason is that Entity Framework LINQ provider does not understand long.Parse and there is no method in SqlFunctions class for this purpose.please use long.Parse()
I am trying to use AddMonths in a query
List<Entities.Subscriber> items = (from s in context.Subscribers
where s.Validated == false && s.ValidationEmailSent == true && s.SubscriptionDateTime < DateTime.Now.AddMonths(-1)
select s).ToList();
But I recieve an error :
LINQ to Entities does not recognize the method 'System.DateTime
AddMonths(Int32)' method, and this method cannot be translated into a
store expression.
Is there a way I can use this function inside my query?
The simplest fix to this is to work out the time limit once before using LINQ:
DateTime limit = DateTime.Now.AddMonths(-1);
List<Entities.Subscriber> items = (from s in context.Subscribers
where s.Validated == false && s.ValidationEmailSent == true &&
s.SubscriptionDateTime < limit)
select s).ToList();
Or more readably IMO:
var items = context.Subscribers
.Where(s => !s.Validated &&
s.ValidationEmailSent &&
s.SubscriptionDateTime < limit)
.ToList();
There's no benefit in using a query expression here, and explicit comparisons with true and false are ugly IMO (unless your properties are of type Nullable<bool> of course).
Jon Skeet has already provided a simple fix, but if you want the DateTime.Now.AddMonths bit to run on the database, try the EntityFunctions.AddMonths method.
This is a more general approach that is especially useful when you cannot replicate the expression cheaply or correctly on the client.
You can change your code to:
DateTime oneMonth = DateTime.Now.AddMonths(-1)
List<Entities.Subscriber> items = (from s in context.Subscribers
where s.Validated == false && s.ValidationEmailSent == true && s.SubscriptionDateTime < oneMonth
select s).ToList();
You have to do this because AddMonth is a .NET function that can't be translated into SQL by Linq to Entities. Perform the calculation in your code and then use the resulting datetime will work.