LINQ to Entities 不识别方法“System.String ToString()”,因此该方法无法转换为存储表达式。
var data = DataSource.Skip(iDisplayStart).Take(iDisplayLength).Select(o => new { MatNR = o.MatNR, MatDB = o.MatDB, CreatedOn=o.CreatedOn.ToString(), CreatedBy = o.CreatedBy, Id2 = o.MatNR });
以上语句就会出现这个提示:LINQ to Entities 不识别方法“System.String ToString()”,因此该方法无法转换为存储表达式。
解决方法有两种
一、使用SqlFunctions
1、
CreatedOn = SqlFunctions.DateName("year", o.CreatedOn) + "-" + SqlFunctions.DateName("month", o.CreatedOn) +"-" + SqlFunctions.DateName("day",o.CreatedOn),
2、
CreatedOn= SqlFunctions.DateName("yyyy", o.CreatedOn) +"-"+ SqlFunctions.StringConvert((decimal)SqlFunctions.DatePart("mm", o.CreatedOn)) +"-"+ SqlFunctions.DateName("dd",o.CreatedOn),
3、
CreatedOn = SqlFunctions.DateName("yyyy", o.CreatedOn) + "-" + SqlFunctions.StringConvert((decimal)SqlFunctions.DatePart("mm", o.CreatedOn)).Trim() + "-" + SqlFunctions.DateName("dd", o.CreatedOn),
注意:月份只有1位数!还不够完美。
二、Linq-to-entities 转换到Linq-to-objects
//Do it in two steps - one L2E query that does the L2E supported part, and a L2O query that does the date formatting and other stuff that is best done in .net code...
////Linq-to-entities query to get the fullname, categoryname, and date
//var query = from c in db.Contacts select new { c.FullName, c.Category.CategoryName, c.DateCreated };
////Linq-to-objects query (.AsEnumerable will separate the L2E from L2O part) that call date formatting methods and other stuff that isn't supported by L2E
//var r = from c in query.AsEnumerable() select new { c.FullName, c.CategoryName, ShortDate = c.DateCreated.ToShortDateString() };
var data = DataSource.Skip(iDisplayStart).Take(iDisplayLength).Select(o => new { MatNR = o.MatNR, MatDB = o.MatDB, CreatedOn=o.CreatedOn, CreatedBy = o.CreatedBy, Id2 = o.MatNR }); var a = from c in data.AsEnumerable() select new { MatNR = c.MatNR, MatDB = c.MatDB, //CreatedOn = Convert.ToDateTime(c.CreatedOn).ToShortDateString(),// 2014/2/28 //CreatedOn = c.CreatedOn.ToString(),//2014/2/28 15:09:40 CreatedOn =c.CreatedOn.ToString("yyyy-MM-dd"),//如果数据库里的日期字段可以为null,则CreatedOn.ToString("yyyy-MM-dd")这种方式是不可以的,如果不为null则可以;
CreatedBy = c.CreatedBy, Id2 = c.MatNR };