LINQ to Entities does not recognize the method? - c#

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);

Related

LINQ Query to Convert numeric to datetime in where clause

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)

LINQ Expression to get member value and can be translated to SQL?

I have a complex query where certain DateTime members of a model entity are being used multiple times, but not always the same members. I'd like to know if I can put the "getting" of the member in an Expression, so I don't have to repeat that piece of code.
A simplified version of my current code looks like this:
var getTargetDate = ((Expression<Func<Order, DateTime>>)(o => o.OrderDate)).Compile();
if (delivery)
getTargetDate = ((Expression<Func<Order, DateTime>>)(o => o.DeliveryDate)).Compile();
return orders.Where(o => getTargetDate(o) >= fromDate && getTargetDate(o) < toDate);
This code compiles, but gives me the runtime Exception:
Exception thrown: 'System.NotSupportedException' in System.Data.Linq.dll
Additional information: Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.
Is there a way to put the "getting" of the DateTime in a variable or method that can be translated to SQL?
This does not literally answer the question, but it does provide a way around the code duplication posed in it.
Put the desired member and the entity itself in an anonymous object, perform the relevant part of the original query on the member, then select out the original entity:
orders = orders.Select(o => new { o,
TargetDate = delivery ? o.DeliveryDate : o.OrderDate
})
.Where(o => o.TargetDate >= fromDate && o.TargetDate < toDate)
.Select(o => o.o);

Linq with data Error condition ( 'Date' is not supported in LINQ)

I am using a LINQ statement to get some data from the table based on data value:
var oDay = diabeticDB.user_data
.Where(y => y.date >= DateTime.Now.Date
& y.BG != null
& y.userid == u)
.Average(x => x.BG).Value;
I get the following error:
The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
The expression contained in Where(...) is converted to SQL, and the EF query provider (that does this conversion) does not understand DateTime.Now.Date.
The expression can contain a specific value, though - so create a local variable for today's date and use that:
var today = DateTime.Now.Date;
var oDay = diabeticDB.user_data
.Where(y => y.date >= today & y.BG != null & y.userid == u)
.Average(x => x.BG).Value;

Convert string to long type and use in a linq query within asp.net MVC

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()

How to query datetime literals and null values in Linq predicate?

In my current query I'm having an error like this:
The datetime literal value '2012-05-24' is not valid.
For regular linq query it seems like this:
_listHistory = (from item in dbase.histories
where item.UserID == details.UserID && item.FriendID.HasValue == true && item.LogDate < today
select item).OrderByDescending(x => x.LogDate).Take(take).Skip(skip).ToList();
I will be dealing with number of table "Columns" so I have to use linq predicate:
string predicate = string.Format("it.UserID=={0} && CAST(it.{1} as Edm.Int64) != null && it.LogDate <= DATETIME'{2}'",
details.UserID, columnname, string.Format("{0:yyyy-MM-dd}", today));
_listHistory = dbase.histories.Where(predicate)
.OrderByDescending(x => x.LogDate).Take(take).Skip(skip).ToList();
But this query result the error above. Can anyone help me to construct my linq query?
It is my first time to deal with Linq predicates and literals.
You could likely use the dynamic LINQ support instead, but assuming this is Entity Query Language, it appears that you can construct the datetime with a call to CreateDateTime:
http://msdn.microsoft.com/en-us/library/bb738563.aspx
CreateDateTime( year, month, day, hour, minute, second)

Categories

Resources