LINQ从DateTime列中选择Month和Month Name

时间:2013-09-29 18:02:08

标签: c# asp.net-mvc entity-framework

我在db中的DateTime列中选择MonthId和MonthName时遇到问题。 我试过这个。它编译但运行时错误 “linq to entities无法识别方法'System.String.ToString()'”

var months = bookings.Select(c => new { 

                MonthId = c.ActualEta.Value.Month,
                MonthName = c.ActualEta.Value.Month.ToString("MMMM")
        }).ToList();

任何? ActualEta在这里是一个可以为空的日期时间。

2 个答案:

答案 0 :(得分:3)

var months = bookings.Select(c => new { 
     MonthId = ((DateTime)c.ActualEta.Value).Month,
     MonthName = ((DateTime)c.ActualEta.Value).ToString("MMMM")
}).ToList();

答案 1 :(得分:2)

var months = bookings
    .AsEnumerable()
    .Select(c => new { 
        MonthId = c.ActualEta.Value.Month,
        MonthName = c.ActualEta.Value.Month.ToString("MMMM")
    }).ToList();

注意AsEnumerable(),这实质上将查询从LinqToEntities转换为LinqToObjects,允许您使用非ToString()之类的SQL方法。