I am trying to render a chart from the following query:
Questionnaires created by month and format the month as mm/YYYY
My code:
public ActionResult QuestionnairesByMonth() {
var query = TrialDB.Questionnaires
.GroupBy(r => new {
Month = r.DateCreated.Month,
Year = r.DateCreated.Year,
})
.Select(group => new {
Date = string.Format("{0}/{1}", group.Key.Year, group.Key.Month),
Total = group.Count()
})
.ToList();
var chart = new Chart(400, 200)
.AddTitle("Questionarios creados por mes")
.DataBind开发者_运维问答Table(query, "Date")
.Write();
return null;
}
but I'm getting the following error :
LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.
I suggest you fetch everything you need in a "simple" Select query which will go to the database, and then perform the formatting locally using AsEnumerable
to switch to an in-process query:
var query = TrialDB.Questionnaires
.GroupBy(r => new {
Month = r.DateCreated.Month,
Year = r.DateCreated.Year,
})
.Select(group => new {
group.Key.Year,
group.Key.Month,
Total = group.Count()
})
.AsEnumerable()
.Select(x => x.Total, Date = string.Format("{0}/{1}", x.Year, x.Month))
.ToList();
Or leave it as a DateTime
when pulling it back from the database, as Stuart suggests:
var query = TrialDB.Questionnaires
.GroupBy(r => new {
Month = r.DateCreated.Month,
Year = r.DateCreated.Year,
})
.Select(group => new {
Date = group.Key,
Total = group.Count()
})
.AsEnumerable()
.Select(x => x.Total,
Date = string.Format("{0}/{1}", x.Date.Year, x.Date.Month))
.ToList();
For more on AsEnumerable()
, read my Edulinq blog post on it.
I think the database itself doesn't understand the string.Format("{0}/{1}", group.Key.Year, group.Key.Month)
- so you'll need to pull back the information as a DateTime, and then format the date in your presentation layer.
精彩评论