Reputation: 5
I have a column TG003 to store date which is a string.
And I want to list data for the past seven days
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.
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.
Upvotes: 0
Views: 6408
Reputation: 2900
I've created a sample that runs in LinqPad without any errors.
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
2/4/2017
2/3/2017
2/2/2017
2/1/2017
1/31/2017
1/30/2017
Upvotes: -1
Reputation: 5550
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.
Upvotes: 2