EF6 IQueryable dynamic linq Where(predicate, values) with DbFunctions.TruncateTime

dynamic-linq entity-framework-6 sql-server

Question

I have an object with the following attributes in my shortened example:

  • Name (string)
  • BirthDateTimeStamp (datetime)

I need to be able to construct dynamic queries in the manner shown below.

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

This is effective. I want to compare my date and time now.

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

This also works well. But what I really want to do when comparing datetimes—and this problem manifests itself more clearly when using equals—is compare dates alone.

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

Since EF to SQL server does not recognize the Date attribute, this is not feasible.

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

Since I can only access my object's properties in the predicate, this is equally ineffective.

How can I approach this problem in such a manner that the predicate maintains its string format? This code is just a small portion of a much larger parser for my queries that cannot be entirely redone.

1
0
1/13/2016 9:10:25 AM

Popular Answer

The solution offered by @RockResolve does work, although it's a bit of a hack. Linq Dynamics offers the ability to implement unique 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();
0
5/16/2018 6:58:29 AM


Related Questions





Related

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