是否可以在Lambda表达式中包含SqlFunctions.StringConvert?

时间:2012-11-27 05:34:53

标签: c# entity-framework-4 lambda expression

我一直在学习表达式并使用下面的代码为数据库模型添加构建表达式(EF4 - ORACLE而不是SQL!)

这完全适用于Oracle,并允许我动态地将"CustomerId", "Contains", 2等谓词构建到f=>f.CustomerId.ToString().ToLower().Contains("2")

但是,如果我尝试对抗SQL Server,那么它会失败,因为我需要调用SqlFunctions.StringConvert - 但我不知道如何将其包含在Lambda中?

我的最终结果将是:

f=> SqlFunctions.StringConvert(f.CustomerId).ToLower().Contains("2")

Thx:)


编辑:添加了我尝试过的示例

这段代码看起来几乎可以工作,有点! 但是,它会在var sqlExpression

上引发错误
Expression of type 'System.Double' cannot be used for parameter of type 'System.Nullable`1[System.Double]' of method 'System.String StringConvert(System.Nullable`1[System.Double])'


MethodInfo convertDouble = typeof(Convert).GetMethod("ToDouble",new Type[]{typeof(int)});
                    var cExp = Expression.Call(convertDouble, left.Body);

                    var entityParam = Expression.Parameter(typeof(TModel), "f");
                    MethodInfo sqlFunc = typeof(SqlFunctions).GetMethod("StringConvert", new Type[] { typeof(double) });
                    var sqlExpression = Expression.Call(sqlFunc, cExp);


                    MethodInfo contains = typeof(string).GetMethod("Contains", new[] { typeof(string) });
                    right = Expression.Constant(value.ToString(), typeof(string));

                    var result = left.AddToString().AddToLower().AddContains(value.ToString());
                    return result;

public static Expression<Func<T, string>> AddToString<T, U>(this Expression<Func<T, U>> expression)
        {

            return Expression.Lambda<Func<T, string>>(
                Expression.Call(expression.Body,
                "ToString",
                null,
                null),
                expression.Parameters);
        }

        public static Expression<Func<T, string>> AddToLower<T>(this Expression<Func<T, string>> expression)
        {

            return Expression.Lambda<Func<T, string>>(
                Expression.Call(expression.Body,
                "ToLower",
                null,
                null),
                expression.Parameters);
        }

        public static Expression<Func<T, bool>> AddContains<T>(this Expression<Func<T, string>> expression, string searchValue)
        {
            return Expression.Lambda<Func<T, bool>>(
                Expression.Call(
                    expression.Body,
                    "Contains",
                    null,
                    Expression.Constant(searchValue)),
                expression.Parameters);
        }

1 个答案:

答案 0 :(得分:4)

我相信你基本上需要构建以下lambda表达式的等效表达式:

e => SqlFunctions.StringConvert((double?) e.Number).Contains("6"))

这是一个完整的复制粘贴示例。它使用CodeFirst所以应该工作而不必创建数据库或类似的东西。只需添加Entity Framework nuget包(我使用的是EF6,但它也适用于EF5)。建立lambda是你真正追求的。

namespace ConsoleApplication8
{
    public class MyEntity
    {
        public int Id { get; set; }
        public int Number { get; set; }
    }


    public class MyContext : DbContext
    {
        public DbSet<MyEntity> Entities { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new MyContext())
            {
                if (!ctx.Entities.Any())
                {
                    ctx.Entities.Add(new MyEntity() {Number = 123});
                    ctx.Entities.Add(new MyEntity() {Number = 1893});
                    ctx.Entities.Add(new MyEntity() {Number = 46});
                    ctx.SaveChanges();
                }

                foreach(var entity in ctx.Entities.Where(e => SqlFunctions.StringConvert((double?) e.Number).Contains("6")))
                {
                    Console.WriteLine("{0} {1}", entity.Id, entity.Number);
                }

                foreach (var entity in ctx.Entities.Where(BuildLambda<MyEntity>("Number", "6")))
                {
                    Console.WriteLine("{0} {1}", entity.Id, entity.Number);
                }

            }
        }

        private static Expression<Func<T, bool>> BuildLambda<T>(string propertyName, string value)
        {
            var parameterExpression = Expression.Parameter(typeof(T), "e");

            var stringConvertMethodInfo = 
                typeof(SqlFunctions).GetMethod("StringConvert", new Type[] {typeof (double?)});

            var stringContainsMethodInfo =
                typeof (String).GetMethod("Contains");

            return 
                Expression.Lambda<Func<T, bool>>(
                Expression.Call(
                    Expression.Call(
                        stringConvertMethodInfo,
                        Expression.Convert(
                            Expression.Property(parameterExpression, "Number"),
                            typeof (double?))),
                    stringContainsMethodInfo,
                    Expression.Constant(value)),
                parameterExpression);
        }
    }
}