[英]LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)'
I have a column TG003 to store date which is a string. 我有一列TG003来存储日期,它是一个字符串。
And I want to list data for the past seven days 我想列出过去7天的数据
Below is what I have done and I'm having errors: 以下是我做过的事情,但有错误:
LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression.
LINQ to Entities无法识别方法'System.DateTime ToDateTime(System.String)',并且该方法无法转换为商店表达式。
public List<CCOPTG> listrecentCCOPTG()
{
string startdate = DateTime.Today.AddDays(-7).ToString("yyyyMMdd");
string enddate = DateTime.Now.ToString("yyyyMMdd");
return db.CCOPTG.Where(p => Convert.ToDateTime(p.TG003)>=Convert.ToDateTime(startdate) && Convert.ToDateTime(p.TG003) <= Convert.ToDateTime(enddate)).OrderByDescending(p=>p.TG003).ToList();
}
Please advise. 请指教。
Try try following 尝试以下
public List<CCOPTG> listrecentCCOPTG()
{
datetime startdate = DateTime.Today.AddDays(-7);
datetime enddate = DateTime.Now;
return db.CCOPTG.Where
(p => p.TG003>=startdate && p.TG003 <= enddate)
.OrderByDescending(p=>p.TG003).ToList();
}
LINQ does not recognise conversion functions so do your conversions first. LINQ无法识别转换功能,因此您首先要进行转换。
I've created a sample that runs in LinqPad without any errors. 我创建了一个在LinqPad中运行且没有任何错误的示例。
void Main()
{
List<CCOPTG> list = new List<CCOPTG>();
for (DateTime i =DateTime.Today.AddDays(-20); i <DateTime.Today; i=i.AddDays(1))
{
list.Add(new CCOPTG { TG003 = i.ToShortDateString()});
}
listrecentCCOPTG( list);
}
public class CCOPTG
{
public string TG003 { get; set;}
}
// Define other methods and classes here
public static void listrecentCCOPTG(List<CCOPTG> list)
{
DateTime startdate = DateTime.Today.AddDays(-7);
DateTime enddate = DateTime.Now;
list.Where
(p => DateTime.Parse(p.TG003) >= startdate && DateTime.Parse(p.TG003) <= enddate)
.OrderByDescending(p => p.TG003).ToList().Dump();
}
This produced the following result: 这产生了以下结果:
2/5/2017 2017/2/5
2/4/2017 2017年2月4日
2/3/2017 2/3/2017
2/2/2017 2017/2/2
2/1/2017 2017/2/1
1/31/2017 2017/1/31
1/30/2017 1/30/2017
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.