开发者

Formatting field in a LINQ expression

开发者 https://www.devze.com 2023-02-19 05:33 出处:网络
I am trying to render a chart from the following query: Questionnaires created by month and format the month as mm/YYYY

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消