0

In my simplified example i have an object with following properties:

  • Name (string)
  • BirthDateTimeStamp (datetime)

I need to ba able to build dynamic queries in the following way

var predicate = "Name = @0";
var values = new object[]{"Ed"};
myIQueryableDataSource.Where(predicate, values)

This work good. Now i want to compare my datetime

var predicate = "BirthDateTimeStamp >= @0";
var values = new object[]{someDateTime};

This works good also. But what i actually want to do when comparing the datetimes and this issue shows itself better when doing the equals is comparing just on date.

var predicate = "BirthDateTimeStamp.Date >= @0";

This is not possible since the Date property is not recognized by EF to SQL server

var predicate = "System.Data.Entity.DbFunctions.TruncateTime(BirthDateTimeStamp) >= @0";

This is also not working since i can only access my object properties in the predicate.

How can i solve this in this way so the predicate stays in the string format. This code is just a part of a big existing parser for my queries and connat be completely rewritten.

JMan
  • 2,611
  • 3
  • 30
  • 51

2 Answers2

0

See https://stackoverflow.com/a/26451213/525788

System.Linq.Dynamic is parsing the expression that you give as C# but does not recognize the class DbFunctions. However you can patch in DbFunctions as a predefined type:

var type = typeof( DynamicQueryable ).Assembly.GetType( "System.Linq.Dynamic.ExpressionParser" );

FieldInfo field = type.GetField( "predefinedTypes", BindingFlags.Static | BindingFlags.NonPublic );

Type[] predefinedTypes = (Type[])field.GetValue( null );

Array.Resize( ref predefinedTypes, predefinedTypes.Length + 1 );
predefinedTypes[ predefinedTypes.Length - 1 ] = typeof( DbFunctions );

field.SetValue( null, predefinedTypes );

Then you can use

var predicate = "DbFunctions.TruncateTime(BirthDateTimeStamp) >= @0";
Community
  • 1
  • 1
RockResolve
  • 1,423
  • 21
  • 29
0

Answer given by @RockResolve did work, but is kind a hack. Linq Dynamics provide functionality to add custom functions

public class CustomTypeProvider: IDynamicLinkCustomTypeProvider
{
    public HashSet<Type> GetCustomTypes()
    {
      HashSet<Type> types = new HashSet<Type>();
      // adding custom types
      types.Add(typeof(DbFunctions)); 
      return types;
    }
}

// use below line to add this to linq
System.Linq.Dynamics.GlobalConfig.CustomTypeProvider = new CustomTypeProvier();