9

I am trying to build dynamic data context, linq is not support dynamic type I found this solution on

http://jrwren.wrenfam.com/blog/2010/03/04/linq-abuse-with-the-c-4-dynamic-type/

public static class ObjectExtensionMethod
{
    public static IEnumerable<dynamic> Select(this object source, Func<dynamic, dynamic> map)
    {
        foreach (dynamic item in source as dynamic)
        {
            yield return map(item);
        }
    }

    public static IEnumerable<dynamic> Where(this object source, Func<dynamic, dynamic> predicate)
    {
        foreach (dynamic item in source as dynamic)
        {
            if (predicate(item))
                yield return item;
        }
    }
}

the problem with this solution is getting all data from database after that applying the where statement. is there any way to apply where statement before getting the data from database with dynamic type

5
  • 1
    I am not sure, how's you are interacting with the database, but using dynamic with database queries, will make the performance poor for your app. Beside, .net already provide Entity Framework to interact with database without your extra effort. Commented Jun 15, 2015 at 5:28
  • 2
    LINQ inspects the compile-time expression tree to translate c# code into SQL statements. As soon as you put in dynamic it ceases to be compile-time, and hence it doesn't work. So, no, you can't use dynamic to query the database. Commented Jun 15, 2015 at 5:32
  • I need to build the queries with dynamic because the database table is built at runtime. after that I am building linq to sql class at run time. after that I need to maintain queries for that table.
    – Bakri
    Commented Jun 15, 2015 at 5:54
  • That still does not mean you need "dynamic". You can use IDataRecord for data rows or object's for hard objects. Commented Jun 15, 2015 at 17:06
  • @Bakri - If you need to use dynamic then you should use the standard data readers rather than try to get LINQ to work. Get your data into memory and then use LINQ-to-objects. Commented Jun 16, 2015 at 1:30

2 Answers 2

2

the problem with this solution is getting all data from database after that applying the where statement.

The problem here is not with dynamic, but with the way you are iterating over the source. You are using foreach, and expect it to be translated to an SQL or sort of, but that is just wrong assumption. As soon as iterator is created by GetEnumerator() method call the query will be "materialized", even if real type of the source is implementing IQueryable<T>, end everything else will be performed in memory.

If you want the conditions to be translated to an SQL you need to implement IQueryableProvider.

Or, at least you can try to call underlying IQueryableProvider. But I'm not sure if it would work.

public static class ObjectExtensionMethod
{
    public static IQueryable Select<T>(this IQueryable source, Expression<Func<dynamic, dynamic>> map)
    {
        var method = new Func<IQueryable<dynamic>, Expression<Func<dynamic, dynamic>>, IQueryable<dynamic>>(Queryable.Select).Method;

        var call = Expression.Call(null, method, source.Expression, Expression.Quote(map));

        return source.Provider.CreateQuery(call);
    }

    public static IQueryable Where(this IQueryable source, Expression<Func<dynamic, bool>> predicate)
    {
        var method = new Func<IQueryable<dynamic>, Expression<Func<dynamic, bool>>, IQueryable<dynamic>>(Queryable.Where).Method;

        var call = Expression.Call(null, method, source.Expression, Expression.Quote(predicate));

        return source.Provider.CreateQuery(call);
    }
}

Please note that type of source parameter has changed from object to IQueryable and types of map and predicate parameters have changed to Expression<Func<,>>.

1
  • thanks @hazzik your solution was really helpful i add the full answer.
    – Bakri
    Commented Jul 7, 2015 at 8:25
0

After long search the solution that is working for me

public static class ObjectExtensionMethod
{
    public static IQueryable Select(this IQueryable source, Expression<Func<dynamic, dynamic>> map)
    {
        try
        {
            var method = new Func<IQueryable<dynamic>, Expression<Func<dynamic, dynamic>>, IQueryable<dynamic>>(Queryable.Select).Method;

            Expression conversion = Expression.Convert(source.Expression, typeof(System.Linq.IQueryable<dynamic>));

            var call = Expression.Call(null, method, conversion, Expression.Quote(map));

            return source.Provider.CreateQuery(call);
        }
        catch (Exception ex)
        {
            return null;
        }
    }

    public static IQueryable Where<T>(this IQueryable source, Expression<Func<T, bool>> predicate)
    {
        try
        {
            var method = new Func<IQueryable<T>, Expression<Func<T, bool>>, IQueryable<T>>(Queryable.Where).Method;

            Expression conversion = Expression.Convert(source.Expression, typeof(System.Linq.IQueryable<T>));

            var call = Expression.Call(null, method, conversion, predicate);

            return source.Provider.CreateQuery(call);
        }
        catch (Exception ex)
        {
            return null;
        }
    }
    public static IEnumerable<dynamic> ToList(this IQueryable source)
    {
        return source as dynamic;
    }
}

the problem know passing Expression<Func<dynamic, dynamic>>
to solve this problem

    public Expression<Func<T, Boolean>> GetWhereFunc<T>(List<WhereCondition> searchFieldList,T item)
    {
        try
        {
            if (searchFieldList == null || searchFieldList.Count == 0)
            {
                return null;
            }
            ParameterExpression pe = Expression.Parameter(item.GetType(), "c");

            //ParameterExpression pe = Expression.Parameter(typeof(object), "c");
            Type itemType = item.GetType();
            //combine them with and 1=1 Like no expression
            Expression combined = null;
            Type tempPropType;
            if (searchFieldList != null)
            {
                foreach (WhereCondition fieldItem in searchFieldList)
                {
                    if (string.IsNullOrEmpty(fieldItem.Value))
                        continue;
                    if (!string.IsNullOrEmpty(fieldItem.GridTblName))
                        continue;
                    //Expression for accessing Fields name property
                    Expression columnNameProperty = Expression.Property(pe, fieldItem.ColumName);

                    //the name constant to match 
                    Expression columnValue = null;
                    tempPropType = itemType.GetProperty(fieldItem.ColumName).PropertyType;

                    if (tempPropType == typeof(DateTime) || tempPropType == typeof(DateTime?))
                    {
                        if (string.IsNullOrEmpty(fieldItem.Value))
                        {
                        }
                        else
                        {

                            DateTime tempdate = DateTime.Parse(fieldItem.Value);
                            TimeZone zoneclient = TimeZone.CurrentTimeZone;
                            TimeSpan spclient = zoneclient.GetUtcOffset(tempdate);
                            tempdate = tempdate.AddMinutes(-1 * spclient.TotalMinutes);
                            fieldItem.Value = tempdate.ToString();
                        }
                    }
                    if (tempPropType == typeof(Guid) || tempPropType == typeof(Guid?))
                    {
                        if (string.IsNullOrEmpty(fieldItem.Value))
                        {
                            columnValue = Expression.Constant(null);
                        }
                        else
                        {
                            if (tempPropType == typeof(Guid?))
                            {
                                columnValue = Expression.Constant((Guid?)Guid.Parse(fieldItem.Value), typeof(Guid?));
                            }
                            else
                            {
                                columnValue = Expression.Constant(Guid.Parse(fieldItem.Value));

                            }
                        }
                    }


                    else if (tempPropType.IsGenericType && tempPropType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        if (string.IsNullOrEmpty(fieldItem.Value))
                        {
                            columnValue = Expression.Constant(null);
                        }
                        else
                        {

                            columnValue = Expression.Constant(Convert.ChangeType(fieldItem.Value, tempPropType.GetGenericArguments()[0])
                                , tempPropType);
                        }
                    }
                    else
                    {
                        columnValue = Expression.Constant(Convert.ChangeType(fieldItem.Value, tempPropType));
                    }
                    Expression e1 = null;
                    MethodInfo method;
                    switch (fieldItem.Cond)
                    {
                        case Condetion.Equal:
                            e1 = Expression.Equal(columnNameProperty, columnValue);
                            break;
                        case Condetion.Greater:
                            e1 = Expression.GreaterThan(columnNameProperty, columnValue);
                            break;
                        case Condetion.GreaterOrEqual:
                            e1 = Expression.GreaterThanOrEqual(columnNameProperty, columnValue);
                            break;
                        case Condetion.Lower:
                            e1 = Expression.LessThan(columnNameProperty, columnValue);
                            break;
                        case Condetion.LowerOrEqual:
                            e1 = Expression.LessThanOrEqual(columnNameProperty, columnValue);
                            break;
                        case Condetion.NotEqual:
                            e1 = Expression.NotEqual(columnNameProperty, columnValue);
                            break;
                        case Condetion.Contaiens:
                            if (fieldItem.IsContaien)
                            {

                                Type tt = fieldItem.Values.GetType();

                                if (tt == typeof(List<dynamic>))
                                {
                                    IEnumerable<dynamic> val = fieldItem.Values.Cast<dynamic>().ToList();
                                    var someValueContain = Expression.Constant(val, val.GetType());
                                    var convertExpression = Expression.Convert(columnNameProperty, typeof(object));
                                    e1 = Expression.Call(someValueContain, "Contains", new Type[] { }, convertExpression);
                                }
                                else
                                {

                                    var mval = fieldItem.Values.AsQueryable().Cast<dynamic>();

                                    var someValueContain = Expression.Constant(mval, mval.GetType());
                                    var convertExpression = Expression.Convert(columnNameProperty, typeof(object));
                                    e1 = Expression.Call((
                                        ((Expression<Func<bool>>)
                                        (() => Queryable.Contains(default(IQueryable<dynamic>), default(object))))
                                        .Body as MethodCallExpression).Method,
                                        someValueContain,
                                        convertExpression);
                                }

                            }
                            else
                            {
                                method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                                var someValueContain = Expression.Constant(fieldItem.Value, columnValue.Type);
                                e1 = Expression.Call(columnNameProperty, method, someValueContain);
                            }
                            break;
                        case Condetion.StartWith:
                            method = typeof(string).GetMethod("StartsWith", new[] { typeof(string) });
                            var someValueStartWith = Expression.Constant(fieldItem.Value, columnValue.Type);
                            e1 = Expression.Call(columnNameProperty, method, someValueStartWith);
                            break;
                        case Condetion.EndWith:
                            method = typeof(string).GetMethod("EndsWith", new[] { typeof(string) });
                            var someValueEndWith = Expression.Constant(fieldItem.Value, columnValue.Type);
                            e1 = Expression.Call(columnNameProperty, method, someValueEndWith);
                            break;
                        case Condetion.NotContaiens:
                            if (fieldItem.IsContaien)
                            {
                                Type tt = fieldItem.Values.GetType();
                                if (tt == typeof(List<dynamic>))
                                {
                                    IEnumerable<dynamic> val = fieldItem.Values.Cast<dynamic>().ToList();
                                    var someValueContain = Expression.Constant(val, val.GetType());
                                    var convertExpression = Expression.Convert(columnNameProperty, typeof(object));
                                    e1 = Expression.Call(someValueContain, "Contains", new Type[] { }, convertExpression);
                                    e1 = Expression.Not(e1);
                                }
                                else
                                {

                                    var mval = fieldItem.Values.AsQueryable().Cast<dynamic>();

                                    var someValueContain = Expression.Constant(mval, mval.GetType());
                                    var convertExpression = Expression.Convert(columnNameProperty, typeof(object));
                                    e1 = Expression.Call((
                                        ((Expression<Func<bool>>)
                                        (() => Queryable.Contains(default(IQueryable<dynamic>), default(object))))
                                        .Body as MethodCallExpression).Method,
                                        someValueContain,
                                        convertExpression);
                                    e1 = Expression.Not(e1);
                                }


                            }
                            else
                            {
                                method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                                var someValueContain = Expression.Constant(fieldItem.Value, columnValue.Type);
                                e1 = Expression.Call(columnNameProperty, method, someValueContain);
                                e1 = Expression.Not(e1);
                            }
                            break;
                    }
                    if (combined == null)
                    {
                        combined = e1;
                    }
                    else
                    {
                        combined = Expression.And(combined, e1);
                    }
                }
            }
            if (combined == null)
            {
                return null;
            }
            var mm = Expression.Lambda<Func<T, bool>>(combined, pe);


            return mm;//.Compile();
        }
        catch (Exception ex)
        {
            Logs.Log(ex);
            return null;
        }
    }


public class WhereCondition
{
    public string ColumName { set; get; }
    public string Value { set; get; }
    public Condetion Cond { set; get; }
    public string GridTblName { set; get; }
    public IEnumerable<dynamic> Values { set; get; }
    public bool IsContaien { set; get; }
    public WhereCondition(string columName, string value, Condetion cond)
    {
        ColumName = columName;
        Value = value;
        Cond = cond;
    }
    public WhereCondition()
    {
        ColumName = "";
        Value = "";
        Cond = Condetion.Equal;
    }
}
public enum Condetion { Equal, Greater, GreaterOrEqual, Lower, LowerOrEqual, NotEqual, Contaiens, NotContaiens, StartWith,EndWith }

We can now call the query like this.

WhereCondition whereCondition = new WhereCondition();
            whereCondition.ColumName = "Id";
            whereCondition.Cond = Condetion.Equal;
            whereCondition.Value = id.ToString();
            Expression<Func<T, bool>> whereEx = GetWhereFunc(new List<WhereCondition>(){whereCondition}, GetType());

            return (from c in RDaynamicContext.GetTable(tbl)
                    select c).Where(whereEx).FirstOrDefault();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.