日期:2014-05-20  浏览次数:20959 次

求个EF中的Linq按月查询的代码
如题:根据网上资料我这样写了
var order = from of in db.orderforms
                        orderby of.StartTime
                        group of by new
                        {
                            of.StartTime.Value.Year,
                            of.StartTime.Value.Month
                        } into g 
                        //orderby g.Key.Year descending,g.Key.Month descending
                        select new 
                        {
                           
                            //Dates=g.Key 
                            Dates = g.Key.Year + "年" + g.Key.Month + "月",
                            orderCount = g.Count()
                        };

可是会报错,报错的是Date值的类型问题{"无法将类型“System.Int32”强制转换为类型“System.Object”。LINQ to Entities 仅支持强制转换 Entity Data Model 基元类型。"},求各位大侠帮忙谢谢啦!!!
------解决方案--------------------
var order = from of in db.orderforms.AsEnumerable()
         

具体报错在哪一行?
------解决方案--------------------
group of by of.StartTime.Value.Year * 12 + of.StartTime.Value.Month
------解决方案--------------------
(from of in db.orderforms
                        orderby of.StartTime
                        group of by new
                        {
                            of.StartTime.Value.Year,
                            of.StartTime.Value.Month
                        } into g select g
).AsEnumerable().Select(g => new { ... })
------解决方案--------------------
Dates = string.Format("{0}年{1}月", g.Key.Year, g.Key.Month)
------解决方案--------------------
也可以试试  在数据库进行转换,调用sql转换函数,进行组装 如
System.Data.Objects.SqlClient.SqlFunctions.DateName("yyyy", of.StartTime)  //2013
System.Data.Objects.SqlClient.SqlFunctions.DateName("MM", of.StartTime)    //10