Dynamic Linq - Methods on type 'Int32?' are not accessible

c# dynamic-linq linq

Question

I am facing a problem since last three days and couldn't find a solution on google and stackoverflow.

I have a nullable int property in my model. When I try applying any function on that column using dynamic where clause, I am facing an error - "Methods on type 'Int32?' are not accessible".

Supposingly, my model structure is -

public class MyTestModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
}

Now, I want to have a search query which is being created dynamically from front end. For example -

Where("Name.StartsWith(\"t\") and ParentId.ToString().StartsWith(\"1\") ");

My solution has catered all other types, but nullable types are not working here. I have also tried checking for null as well, but doesn't work. (Read this from some other forum):

Where("Name.StartsWith(\"t\") and (ParentId != null and ParentId.ToString().StartsWith(\"1\")) ");

Where("Name.StartsWith(\"t\") and (ParentId != null and ((int?)ParentId).ToString().StartsWith(\"1\")) ");
1
1
8/13/2015 9:54:36 AM

Accepted Answer

Try ParentId.Value.ToString().StartsWith(\"1\"). You don't need to check for null values if the query will be executed on an SQL server, because there is no NULL exceptions in SQL. If the query will be executed "locally" (against a .NET collection) you have to check for null values.

0
8/13/2015 10:00:45 AM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow