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

微笑、不失礼 提交于 2020-01-30 08:29:44

问题


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


回答1:


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



回答2:


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.




回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/16811453/convert-string-to-long-type-and-use-in-a-linq-query-within-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!