Entity Framework 4.0 Entity SQL passing null ObjectParameter parameters

限于喜欢 提交于 2019-12-23 09:02:02

问题


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();

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 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.

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


回答1:


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();

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

Davide




回答2:


Nice post Davide, I used this fix to pass an integer value;

var prm = new ObjectParameter("pName", typeof(int));
prm.Value = pmId;


来源:https://stackoverflow.com/questions/4815317/entity-framework-4-0-entity-sql-passing-null-objectparameter-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!