表达式树和空类型 [英] Expression Trees and Nullable Types

查看:302
本文介绍了表达式树和空类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩弄表达式树。我有一个执行由动态创建一个表达式树的查询以下简单的方法。是的ItemType在数据库中可空INT,的,并在EF实体类的。出于某种原因,虽然查询抛出

I've been playing around with Expression Trees. I have the following simple method that performs a query by dynamically creating an Expression Tree. ItemType is a nullable int in the database, and also in the EF entity class. For some reason though the query throws the error of

未处理的异常的错误:
System.InvalidOperationException:在
二元运算符等于没有定义
的各类
'System.Nullable`1 [System.Int32]'和
'System.Int32'。

Unhandled Exception: System.InvalidOperationException: The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.

我不认为我问EF任何东西转换。我得定义为 INT?我的参数,这是我认为是应该的。

I don't think I'm asking EF to convert anything. I've got my parameter defined as int?, which is what I thought it should be.

请注意,我看着这个

在表达式目录树与空类型工作

不过这家伙试图在类型为对象为空的他int值,我想这EF必须通过问题。实际上,我宣布这是正确类型的从头

But this guy is trying to pass in his nullable int value typed as object, which EF I guess has problems with. I'm actually declaring this as the right type ab initio.

   public void GetResultCollection<T>() {
        MyEntities db = new MyEntities();
        var result = db.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name + "s"));

        int? ItemTypeValue = 1;

        var param = Expression.Parameter(typeof(T));

        var lambda = Expression.Lambda<Func<T, bool>>(
            Expression.Equal(
                Expression.Property(param, "ItemType"),
                Expression.Constant(ItemTypeValue)),
            param);

        var list = result.Where(lambda).ToList();
    }

修改

我也试过 ItemTypeValue.Value - 同样的错误。

I've also tried ItemTypeValue.Value - same error

推荐答案

我认为你需要将其转换

var right = Expression.Constant(ItemTypeValue , typeof(int?))
....

 var lambda = Expression.Lambda<Func<T, bool>>(
            Expression.Equal(
                Expression.Property(param, "ItemType"),
                right),
            param);

这篇关于表达式树和空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆