I have a SQL stored procedure and I need to be able to pass a NULL
as a value to one of its parameters to be used in a query like this:
create procedure sp
@param1 varchar(30)
as
select * from tabl开发者_StackOverflowe where field = isnull(@param1, field)
So I need to some how tell EF to make @param1
nullable. How do I do this?
Thanks!
In case it helps, the process I use with EF is:
- Create SP
- Update Model (edmx)
- Add new function import
- Generate new complex type by clicking the button
- Run Custom Tool on separate template file (to generate POCO)
As a work-around, you could declare two separate stored procedures:
-- use this for non-null parameters
create procedure sp
@param1 varchar(30)
as
select * from table where field = @param1
-- use this for null
create procedure sp_null
as
select * from table
and then you can write the desired abstraction in C#:
public ... GetSp(string param1)
{
if (param1 == null)
return ....sp_null();
else
return ....sp(param1);
}
Quick look and I found this on stackoverflow. Hope it helps.
Entity Framework 4.0 Entity SQL passing null ObjectParameter parameters
Use DBNull.Value
, I've done exactly this with one of my stored procedures. To call your procedure my code would look like:
List<ObjectParameter> objectParameterList = new List<ObjectParameter>();
if (string.IsNullOrEmpty(param1))
{
object nullValue = DBNull.Value;
objectParameterList.Add(new ObjectParameter("param1", nullValue));
}
else
{
objectParameterList.Add(new ObjectParameter("param1", param1));
}
context.ExecuteFunction("MyEFModel.sp", objectParameterList.ToArray());
Hopefully this helps.
set the default value in Stored procedure as NULL.
create procedure sp
@param1 varchar(30) =NULL
as
select * from table where field = isnull(@param1, field)
精彩评论