0

I'm having trouble selecting MonthId and MonthName from a DateTime column in db. I've tried this. It compiles but runtime error "linq to entities does not recognize the method 'System.String.ToString()'"

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

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

Anyone? ActualEta is an nullable datetime here.

4

2 回答 2

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

请注意AsEnumerable(),这实际上将查询从 LinqToEntities 转换为 LinqToObjects,从而允许您使用非 SQL 方法,例如ToString().

于 2013-09-29T18:06:41.877 回答
3
var months = bookings.Select(c => new { 
     MonthId = ((DateTime)c.ActualEta.Value).Month,
     MonthName = ((DateTime)c.ActualEta.Value).ToString("MMMM")
}).ToList();
于 2013-09-29T18:07:33.640 回答