简体   繁体   中英

LINQ to Entities does not recognize the method 'System.String GetMonthName(Int32)' method

What am I doing wrong? FYI The repository method GetResearchArticles() returns an IQueryable.

var grouped = (from p in _researchArticleRepository.GetResearchArticles()
               group p by new { month = p.DatePublished.Month, year = p.DatePublished.Year } into d
               select new
               {
                   dt = d.Key.month + "-" + d.Key.year,
                   dtByMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(d.Key.month) + " " + d.Key.year
               }//count = d.Count() }
               )
               .OrderByDescending(g => g.dt);
return grouped.ToDictionary(item => item.dt, item => item.dtByMonthName);

It is probably trying to convert that statement to a SQL expression, which it cannot do. Instead of trying to do that on the database, you should make that call on data that has already been retrieved from the database.

Basically, you need to run .ToList() or something to force the fetching of the data, and then make a call to GetMonthName()

since your not doing any filtering this should work but your pulling out all research articles into memory because SQL doesnt understand how to get month

var grouped = (from p in _researchArticleRepository.GetResearchArticles().ToList()
                   group p by new { month = p.DatePublished.Month, year = p.DatePublished.Year } into d
                   select new
                   {
                       dt = d.Key.month + "-" + d.Key.year,
                       dtByMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(d.Key.month) + " " + d.Key.year
                   }//count = d.Count() }
                   )
                   .OrderByDescending(g => g.dt);
    return grouped.ToDictionary(item => item.dt, item => item.dtByMonthName);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM