eftable表映射以后的代码以下:html
public partial class eftable { public int id { get; set; } public string name { get; set; } public Nullable<int> age { get; set; } public Nullable<System.DateTime> efdate { get; set; } }
按日期时间查询代码以下:express
private void button1_Click(object sender, EventArgs e) { testEntities db = new testEntities(); DateTime dt2 = DateTime.Parse("2018/5/23 8:45:28"); var ef = db.eftable.Where<eftable>(feftable => compareDateTimesecond(feftable.efdate ,dt2)>2); var counts = ef.Count(); foreach(var item in ef) { Console.WriteLine(item.id + ":" + item.name + ":" + item.age); } } private int compareDateTimesecond(Nullable<DateTime> dtsrc, DateTime dtdes) { if (!dtsrc.HasValue) return -1; TimeSpan tssrc = new TimeSpan(dtsrc.Value.Ticks); TimeSpan tsdes = new TimeSpan(dtdes.Ticks); TimeSpan ts = tssrc.Subtract(tsdes).Duration(); return ts.Seconds; }
我将断点打在compareDateTimesecond函数中的第一句上,但调试时不进入断点处,直接运行到var counts =ef.Count()处,而且老是出现:函数
“System.NotSupportedException”类型的未经处理的异常在 EntityFramework.dll 中发生 其余信息: LINQ to Entities does not recognize the method 'Int32 compareDateTimesecond(System.Nullable`1[System.DateTime], System.DateTime)' method, and this method cannot be translated into a store expression.
根据 https://www.cnblogs.com/wusir/p/3477435.html 所说,本表达式只是LINQ to Entities,而不是真正的C#语言,虽然上述代码在编译是没有错误,但运行时,转换为SQL就产生了错误,没法转换为存储表达式。this
解决办法是:将用户输入的起始日期的转换提早一步,使用真正的C#代码完成,而后将转换后的变量代入到LINQ表达式内。https://blog.csdn.net/qiujuer/article/details/41868331 中有一个推荐方法,我修改以后的代码以下:.net
var ef = db.eftable.ToList().Where(f => f.efdate > dt2 && f.efdate < dt3).OrderByDescending(i => i.id).Skip(2).Take(3).Select(u => new { name = u.name, age = u.age, id = u.id, efdate = u.efdate }); foreach(var item in ef) { Console.WriteLine(":" + item.name + ":" + item.age + ":" + item.efdate.ToString()); }