1

I can use PadLeft() method in Razor View as shown below without any problems:

@Model.Project.PKey - @Model.IssueNum.ToString().PadLeft(5, '0')

However, I cannot create the same statement in the controller using the same viewmodel:

var result = dataContext.Select(m => new
            IssueViewModel
            {
                ID = m.ID,
                ProjectID = m.ProjectID
                Key = m.Project.PKey + "-" + m.IssueNum.ToString().PadLeft(5, '0')
            }
        ).ToDataSourceResult(request);

Do you have any idea about how to use PadLeft() method in this lambda expression?

Jack
  • 1
  • 21
  • 118
  • 236

1 Answers1

2

You need to bring your data into memory from your data source before using PadLeft:

var result = dataContext.Select(
    m => new { // Make a projection of all columns we need into an anonymous type
        ID = m.ID,
        ProjectID = m.ProjectID,
        PKey = m.Project.PKey,
        IssueNum = m.IssueNum
    }) // Now bring the result from the data source into memory
    .AsEnumerable()
    // We are ready to make IssueModel from the parts prepared above:
    .Select(m => new IssueModel {
         ID = m.ID,
         ProjectID = m.ProjectID,
         Key = m.PKey + "-" + m.IssueNum.ToString().PadLeft(5, '0')
     })
     .ToDataSourceResult(request);

Now the creation of IssueModel is done by LINQ-to-Object, which supports PadLeft.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523