实体框架4.0实体SQL传递null ObjectParameter参数 [英] Entity Framework 4.0 Entity SQL passing null ObjectParameter parameters

查看:241
本文介绍了实体框架4.0实体SQL传递null ObjectParameter参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体运行的SQL语句:

I have an Entity SQL query:

SELECT VALUE t FROM MyEntities AS t 
WHERE t.Name = @p OR (@p IS NULL AND t.Name IS NULL)

我可以执行查询,如下所示:

I can execute the query as follows:

var results = context.CreateQuery<WorkflowInstance>(
    query, new ObjectParameter("p", name)).ToList();

但是,如果'名'变量为空,然后我得到了System.ArgumentNullException。所以,我也尝试过使用的DBNull.Value如果名称为空,我也得到了以下异常:

However, if the 'name' variable is null, then I get the System.ArgumentNullException. So I also tried to use DBNull.Value if the name was null, and I get the following exception:

System.ArgumentOutOfRangeException被抓
  消息=指定   参数类型System.DBNull不是   有效。仅标量类型,如   System.Int32中,System.Decimal,   System.DateTime的,和的System.Guid,是   支持的。

System.ArgumentOutOfRangeException was caught
Message=The specified parameter type 'System.DBNull' is not valid. Only scalar types, such as System.Int32, System.Decimal, System.DateTime, and System.Guid, are supported.

我想有参数化查询,其中空值也是可能的参数值。我如何做到这一点与实体SQL?

I would like to have parameterized queries where null values are also possible parameter values. How do I achieve this with Entity SQL?

推荐答案

您是对的,似乎是在ObjectParameter构造函数中的一个错误。 但是,Value属性似乎接受空值。 尝试替换您的code:

You are right, seems to be a bug in the ObjectParameter constructor. But the Value property seems to accept null values. Try to replace your code with:

var prm = new ObjectParameter("p", typeof(string));
prm.Value = name;

var results = context.CreateQuery<WorkflowInstance>(
    query, prm).ToList();

如果您指定的参数值直接在code似乎工作。

If you assign the Value parameter directly the code seems to work.

达维德

这篇关于实体框架4.0实体SQL传递null ObjectParameter参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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