Windows Phone LocalDB Method has no supported translation to SQL - linq

I want compare datetime (i need parse it) with now in LINQ query
From i In db.Downloads
Where i.WantExpiration And DateTime.Parse(i.Expiration) < DateTime.Now
Everytime i get error: Method 'System.DateTime Parse(System.String)' has no supported translation to SQL.
How i can in LINQ to SQL parse datetime?

You could do this:
From i In db.Downloads
Where i.WantExpiration And i.Expiration < DateTime.Now
provided that Expiration is a DateTime column in your DB.
The error you are getting is expected since LINQ-SQL translates our linq queries in sql and then send them in the db, where there are executed and the results travel back to us. That being said, there isn't something similar like DateTime.Parse() in sql, so this method cannot be converted to a corresponding one in SQL. Hence your query cannot be translated in SQL.
If Expiration isn't a DateTime column in your DB, then you could make the following trick
(I see that you query is written in VB, but since I don't use VB, I will write my own in C# and subsequently, you could change it to VB.)
// Initially you will get all your data in memory.
var query = (from d in db.Downloads
select d).AsEnumerable();
// Then you will query the in memory data.
var data = (from q in query
where q.WantExpiration &&
DateTime.Parse(q.Expiration) < DateTime.Now);

Related

How to return a query from cosmos db order by date string?

I have a cosmos db collection. I need to query all documents and return them in order of creation date. Creation date is a defined field but for historical reason it is in string format as MM/dd/yyyy. For example: 02/09/2019. If I just order by this string, the result is chaos.
I am using linq lambda to write my query in webapi. I have tried to parse the string and try to convert the string. Both returned "method not supported".
Here is my query:
var query = Client.CreateDocumentQuery<MyModel>(CollectionLink)
.Where(f => f.ModelType == typeof(MyModel).Name.ToLower() && f.Language == getMyModelsRequestModel.Language )
.OrderByDescending(f => f.CreationDate)
.AsDocumentQuery();
Appreciate for any advice. Thanks. It will be huge effort to go back and modify the format of the field (which affects many other things). I wish to avoid it if possible.
Chen Wang.Since the order by does not support derived values or sub query(link),so you need to sort the derived values by yourself i think.
You could construct the MM/dd/yyyy to yyyymmdd by UDF in cosmos db.
udf:
function getValue(datetime){
return datetime.substring(6,10)+datetime.substring(0,2)+datetime.substring(3,5);
}
sql:
SELECT udf.getValue(c.time) as time from c
Then you could sort the array by property value of class in c# code.Please follow this case:How to sort an array containing class objects by a property value of a class instance?

Count maching date data [duplicate]

I need to call ToShortDateString in a linq query suing lambda expressions:
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date.ToShortDateString() == shortDateString);
but I get the error:
An exception of type 'System.NotSupportedException' occurred in
System.Data.Entity.dll but was not handled in user code
Additional information: LINQ to Entities does not recognize the method
'System.String ToShortDateString()' method, and this method cannot be
translated into a store expression.
What can I do, considering that I do need to use ToShortDateString() ?
Thanks.
Linq to Entities cannot convert ToSortDateString method into SQL code. You can't call it on server side. Either move filtering to client side (that will transfer all data from server to client), or consider to use server-side functions to take date part of date (you should pass DateTime object instead of shortDateString):
EntityFunctions.TruncateTime(p.date) == dateWithoutTime
You shouldn't be forcing a string comparison when what you're working with is Date/time data - as soon as you force string comparisons, you're suddenly having to deal with how the strings are formatted.
Instead, have something like:
var endDate = targetDate.AddDays(1);
toRet.Notification = Repositories
.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date >= targetDate && p.date < endDate);
(Assuming that targetDate is whatever DateTime variable you had that was used to produce shortDateString in your code, and is already a DateTime with no time value)
Try this,
You can also used with below code.
Activity = String.Format("{0} {1}", String.Format("{0:dd-MMM-yyyy}", s.SLIDESHEETDATE), String.Format("{0:HH:mm}", s.ENDDATETIME))
ToShortDateString() method usually used to work only with date and ignore time stamps.
You will get exactly today result-set by using the following query.
Repositories.portalDb.portal_notifications.OrderByDescending(p => p.id)
.FirstOrDefault(p => p.date.Date == DateTime.Now.Date);
By using Date property of DateTime struct you can just fetch record of that date only.
Note: Linq to Objects. Only works if you CAN (or have option) to bypass ToShortDateString() method

How can I use Math.X functions with LINQ?

I have a simple table (SQL server and EF6) Myvalues, with columns Id & Value (double)
I'm trying to get the sum of the natural log of all values in this table. My LINQ statement is:
var sum = db.Myvalues.Select(x => Math.Log(x.Value)).Sum();
It compiles fine, but I'm getting a RTE:
LINQ to Entities does not recognize the method 'Double Log(Double)' method, and this method cannot be translated into a store expression.
What am I doing wrong/how can I fix this?
FWIW, I can execute the following SQL query directly against the database which gives me the correct answer:
select exp(sum(LogCol)) from
(select log(Myvalues.Value) as LogCol From Myvalues
) results
LINQ tries to translate Math.Log into a SQL command so it is executed against the DB.
This is not supported.
The first solution (for SQL Server) is to use one of the existing SqlFunctions. More specifically, SqlFunctions.Log.
The other solution is to retrieve all your items from your DB using .ToList(), and execute Math.Log with LINQ to Objects (not LINQ to Entities).
As EF cannot translate Math.Log() you could get your data in memory and execute the function form your client:
var sum = db.Myvalues.ToList().Select(x => Math.Log(x.Value)).Sum();

LINQ Convert string to datetime

In SQL I do it like this:
DateMonth=convert(datetime, convert(char(6), AASI.Inv_Acctcur) + '01')
How to do it in LINQ? String is in following format:
"yyyyMMdd"
Thanks,
Ile
EDIT:
Example of SQL usage:
SELECT convert(datetime, '20161023', 112) -- yyyymmdd
Found here: http://www.sqlusa.com/bestpractices/datetimeconversion/
This page on MSDN documentation lists all convert methods that LINQ to SQL does not support.
Convert.ToDateTime is not listed in there. So, I guess you could just use Convert.ToDateTime to do what you want.
This is not something typically for LINQ or any LINQ over Expression trees enabled provider (such as LINQ to SQL, LINQ to Entities, LINQ to NHibernate, LLBLGen Pro, etc, etc). This is simply a language question. You want to know how to convert the format yyyyMMdd to a DateTime.
The trick is to leave the conversion OUT of your LINQ (over Expression trees) query, because a LINQ provider will not be able to convert it, or if it can, you will get very provider specific implementation.
Therefore, the trick is to get it out of the database as a string (or of course even better: change your database model) and convert it to a DateTime in .NET. For instance:
// Doing .ToArray is essential, to ensure that the
// query is executed right away.
string[] inMemoryCollectionStrings = (
from item in db.Items
where some_condition
select item.Inv_Acctcur).ToArray();
// This next query does the translation from string to DateTime.
IEnumerable<DateTime> dates =
from value in inMemoryCollectionStrings
select DateTime.ParseExact(value, "yyyyMMdd",
CultureInfo.InvariantCulture);
In other words, you can use the following line to make the conversion:
DateTime.ParseExact(value, "yyyyMMdd", CultureInfo.InvariantCulture);

Linq to NHibernate generating 3,000+ SQL statements in one request!

I've been developing a webapp using Linq to NHibernate for the past few months, but haven't profiled the SQL it generates until now. Using NH Profiler, it now seems that the following chunk of code hits the DB more than 3,000 times when the Linq expression is executed.
var activeCaseList = from c in UserRepository.GetCasesByProjectManagerID(consultantId)
where c.CompletionDate == null
select new { c.PropertyID, c.Reference, c.Property.Address, DaysOld = DateTime.Now.Subtract(c.CreationDate).Days, JobValue = String.Format("£{0:0,0}", c.JobValue), c.CurrentStatus };
Where the Repository method looks like:
public IEnumerable<Case> GetCasesByProjectManagerID(int projectManagerId)
{
return from c in Session.Linq<Case>()
where c.ProjectManagerID == projectManagerId
select c;
}
It appears to run the initial Repository query first, then iterates through all of the results checking to see if the CompletionDate is null, but issuing a query to get c.Property.Address first.
So if the initial query returns 2,000 records, even if only five of them have no CompletionDate, it still fires off an SQL query to bring back the address details for the 2,000 records.
The way I had imagined this would work, is that it would evaluate all of the WHERE and SELECT clauses and simply amalgamate them, so the inital query would be like:
SELECT ... WHERE ProjectManager = #p1 AND CompleteDate IS NOT NULL
Which would yield 5 records, and then it could fire the further 5 queries to obtain the addresses. Am I expecting too much here, or am I simply doing something wrong?
Anthony
Change the declaration of GetCasesByProjectManagerID:
public IQueryable<Case> GetCasesByProjectManagerID(int projectManagerId)
You can't compose queries with IEnumerable<T> - they're just sequences. IQueryable<T> is specifically designed for composition like this.
Since I can't add a comment yet. Jon Skeet is right you'll want to use IQueryable, this is allows the Linq provider to Lazily construct the SQL. IEnumerable is the eager version.

Resources