Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading zeros with LINQ and Entity Framework

I try to add leading zeros in my ASP MVC application via Linq:

int length = 4;
IEnumerable<object> query = [...]
select new
    {
        Seq = a.Seq.ToString("D" + length),
    }).OrderBy(a =>a.Seq).ToList();

.. but I receive the following error:

Additional information: LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

What is the correct method to do this?

like image 228
Citizen SP Avatar asked Nov 30 '15 08:11

Citizen SP


1 Answers

I think String.PadLeft is supported (at least in Linq-To-Sql it works):

Seq = a.Seq.PadLeft(length, '0')}

If that doesn't work (i cannot test it) you can use SqlFunctions.Replicate:

Seq = SqlFunctions.Replicate("0", length - a.Seq.ToString().Length) + a.Seq

(the length calculation needs to be revised, i hope you get the idea)

like image 53
Tim Schmelter Avatar answered Sep 28 '22 00:09

Tim Schmelter