Search code examples
entity-frameworklinqlinq-to-entities

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?


Solution

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