I have a database with a ValidDate field – it’s a string(we made a mistake, it should be a datetime, but we can’t modify the database now.)
and now I want to compare this filed with a parameter(validDateStart) from the website:
priceList = priceList.Where(p => Convert.ToDateTime(p.ValidDate) >= Convert.ToDateTime(validDateStart));
var list = initPriceList.ToList();
But I get an error: The method ToDateTime is not implemented.
Can anybody give me some help? Thanks!
This is not supported in Linq to Entities (nor Linq to SQL to my knowledge). Remember that your query is executed on the database – where there is simply no equivalent for
Convert.ToDateTime.Any string parsing in your query would really just be a workaround – as a real solution make those columns not strings but
datetimein the database and you would not have this problem in the first place.A hacky workaround would be materializing all rows (you can use
AsEnumerable()for that), then doing the parsing – this will have bad performance though but might work good enough if there are few rows:Edit:
With your example update it looks like you can just do string comparisons to do what you wanted – granted it’s still a hack but would perform much better than materializing all rows. This is possible because your date format puts the most significant numbers first, then the less significant parts – it’s year, then month, then day (should this not be the case and the day comes before the month in your example this solution will not work).
Assuming your input string
validDateStartis in the same format as well you can just do:string comparison with
String.CompareToseems to be support both in Linq to Sql as well as Linq to Entities.