不能在lambda表达式

时间:2015-08-25 21:12:29

标签: asp.net-mvc linq asp.net-mvc-4 lambda padleft

我可以在Razor View中使用PadLeft()方法,如下所示,没有任何问题:

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

但是,我无法使用相同的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);

您对此PadLeft()中如何使用lambda expression方法有任何想法吗?

1 个答案:

答案 0 :(得分:2)

在使用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);

现在IssueModel的创建由LINQ-to-Object完成,它支持PadLeft