使用LINQ和Entity Framework添加前导零

Cit*_* SP 4 linq linq-to-entities entity-framework

我尝试通过Linq在我的ASP MVC应用程序中添加前导零:

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

..但我收到以下错误:

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.
Run Code Online (Sandbox Code Playgroud)

这样做的正确方法是什么?

Tim*_*ter 16

我认为String.PadLeft是支持的(至少在Linq-To-Sql中它可以工作):

Seq = a.Seq.PadLeft(length, '0')}
Run Code Online (Sandbox Code Playgroud)

如果这不起作用(我无法测试)你可以使用SqlFunctions.Replicate:

Seq = SqlFunctions.Replicate("0", length - a.Seq.ToString().Length) + a.Seq
Run Code Online (Sandbox Code Playgroud)

(长度计算需要修改,希望你明白了)

  • `String.PadLeft()` 在 Linq to Entities 中不起作用,但 `SqlFunctions.Replicate()` 可以。 (2认同)