Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a null value into a stored procedure with Entity Framework?

I have an MVC application using Entity Framework. I want to pass a parameter having a null value to a stored procedure. I want to pass MerchantID as null in some cases.

GetValues(int[] TicketID,int? MerchantID,bool IsOpen)
{

//TicketID has values 1123,1122 etc
//MerchantID sometimes null
//IsOpen true/false

  DataTable tbldepartmentid = new DataTable("Departmentid");
  tbldepartmentid.Columns.Add("VALUE", typeof(int));
  
  foreach (var id in TicketID)
      tbldepartmentid.Rows.Add(id);

 List<GetTroubleTicketDetails_Result> GetTroubleTicketDetails = _getTroubleTicketDetails_Result.ExecuteCustomStoredProc("Tickets.GetDetails", " @GroupID,@MerchantID,@Open",
                 new SqlParameter("GroupID", SqlDbType.Structured) { Value = tbldepartmentid, TypeName = "dbo.tblTVPForCSVINT" }
                 , new SqlParameter("MerchantID", MerchantID)
                 , new SqlParameter("Open", IsOpen)).ToList();
                return GetTroubleTicketDetails;
}

My problem is that when I pass MerchantID=null, it gives me the below error:

"The parameterized query '(@GroupID [dbo].[tblTVPForCSVINT] READONLY,@MerchantID nvarchar(' expects the parameter '@MerchantID', which was not supplied."

How can I pass a null value for MerchantID?

like image 971
skiskd Avatar asked Jul 03 '15 07:07

skiskd


1 Answers

You need to pass SqlInt32.Null instead of null as follows:

new SqlParameter("MerchantID", MerchantID ?? SqlInt32.Null)
like image 126
Jurgen Camilleri Avatar answered Oct 03 '22 00:10

Jurgen Camilleri