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
?
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
.