Gmorken
Gmorken

Reputation: 443

LINQ select MonthId and MonthName from DateTime column

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.

Upvotes: 0

Views: 9121

Answers (2)

devuxer
devuxer

Reputation: 42364

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

Note the AsEnumerable(), this essentially converts the query from LinqToEntities to LinqToObjects, allowing you to use non-SQL methods like ToString().

Upvotes: 2

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

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

Upvotes: 3

Related Questions