Paradox
Paradox

Reputation: 129

No applicable method 'Parse' exists in type 'DateTime'

I get the exception "No applicable method 'Parse' exists in type 'DateTime'" when I run the following code:

var truncatedData = new object();
string TableName = "Products";
string ColumnName = cboAdvSearchCol1.Text.ToString();
var rawData = twr.GetType().GetProperty(TableName).GetValue(twr, null);
string query = ColumnName + ">= DateTime.Parse(" + txtAdvSearchVal1.Text +") && " + ColumnName + "< DateTime.Parse("
+ txtAdvSearchVal1.Text +").AddDays(1)";
truncatedData = ((IQueryable<object>)rawData).Where(query).ToList();//I get exception here

while debugging, I get the value of (string) query as "RUNTIMESTAMP>= DateTime.Parse(7/30/2015) && RUNTIMESTAMP< DateTime.Parse(7/30/2015).AddDays(1)" Please note that I am using dynamic linq.

Upvotes: 3

Views: 3028

Answers (1)

You generate the following code for your dynamic expression: DateTime.Parse(7/30/2015). However, it's not doing what you're expecting.

Since there are no quotes surrounding the date, the expression 7 / 30 / 2015 is interpreted as integer division, like this:

7 / 30 / 2015 = (7 / 30) / 2015 = 0 / 2015 = 0

So, the result is the same as DateTime.Parse(0), but DateTime.Parse only accepts string as an argument. Since a method accepting an int is not found, you get the exception about no applicable method.

The correct way to call it would be:

string query = ColumnName + ">= DateTime.Parse(\"" + txtAdvSearchVal1.Text +"\") && "
    + ColumnName + "< DateTime.Parse(\"" + txtAdvSearchVal1.Text +"\").AddDays(1)";

Notice the extra " symbols to use the date as a string.

Upvotes: 1

Related Questions