0

I have a problem converting int (long) to string. It throws me an exception when I am using l.code == l.id.ToString(). id is type long and code is nvarchar.

The code i am using is

if (municipalityId != null)
    q = q.Where(l => l.MunicipalityId == municipalityId.Value && l.Code == l.Id.ToString());

Any help I would appreciate

fubo
  • 44,811
  • 17
  • 103
  • 137
user2568960
  • 65
  • 1
  • 11
  • 3
    What is the exception exactly? – Soner Gönül Apr 08 '15 at 12:02
  • What is the exception and its message that you get ? – Zealous System Apr 08 '15 at 12:02
  • what type is `q` collection? Is it `IQueryable` and exposed from EF ? – Yura Apr 08 '15 at 12:06
  • 1
    Sorry. The exception is: LINQ to Entities does not recognize the method 'System.String ToString(Int64)' method, and this method cannot be translated into a store expression. – user2568960 Apr 08 '15 at 12:07
  • I a posting my method : var q = _service.GetLocalities() .Select(LocalityViewModel.FromEntityExpression) .UnwrapLocalizedQuery(); if (municipalityId != null) q = q.Where(l => l.MunicipalityId == municipalityId.Value && l.Code == l.Id.ToString()); q = q.OrderBy(l => l.Name); return Json(q.ToList(), JsonRequestBehavior.AllowGet); – user2568960 Apr 08 '15 at 12:08
  • what version of entity framework are you using? – rdans Apr 08 '15 at 12:09
  • As the exception says, you just cannot use .ToString() in a LINQ to Entities expression. – kelsier Apr 08 '15 at 12:15
  • Same problem is face here http://stackoverflow.com/questions/1066760/problem-with-converting-int-to-string-in-linq-to-entities – Reena Apr 08 '15 at 12:20

1 Answers1

0

As Matt Thrower pointed out - this is problem in EF converting ToString() method into actual SQL type converting.

Try specifying SQL Function explicitly:

if (municipalityId != null)
q = q.Where(l => l.MunicipalityId == municipalityId.Value && l.Code == SqlFunctions.StringConvert((decimal)l.Id).Trim())
Community
  • 1
  • 1
Yura
  • 2,013
  • 19
  • 25