Binding empty list or null value to table valued parameter on a stored procedure (.net)

本小妞迷上赌 提交于 2019-12-02 17:49:50

The trick is: don’t pass in the parameter at all. The default value for a table-valued parameter is an empty table.

It is a shame that the exception message is so unhelpful.

Not passing a value does work but not in the case where I had multiple table value parameters to pass into the procedure. How I solved it was to specify a value of DEFAULT in my query string. For example,

string sqlQuery = "[dbo].[GetOrderData] @QueueId";

if (OrderIdList.Any())
{
    sqlQuery = sqlQuery + ", @OrderIdList";
}
else
{
    sqlQuery = sqlQuery + ", DEFAULT";
}

if (RegionIdList.Any())
{
    sqlQuery = sqlQuery + ", @RegionIdList";
}
else
{
    sqlQuery = sqlQuery + ", DEFAULT";
}

Kudos to http://www.sommarskog.se/arrays-in-sql-2008.html#Invoking where I found the solution for this.

I was a bit confused by what the 'not passing the parameter' statement means. What ends up working for Entity Framework ExecuteSqlCommandAsync() is this:

  new SqlParameter("yourParameterName", SqlDbType.Structured)
  {
      Direction = ParameterDirection.Input,
      TypeName = "yourUdtType",
      Value = null
  };

This will pass the parameter as 'default'.

I get the error when passing an empty IEnumerable<int> but it works fine when I pass an empty List<int> instead.

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