我想在Web API控制器中执行具有用户定义的表类型的存储过程。
以下是控制器的代码:
public IHttpActionResult PostTableForDTProductCodePO([FromBody] List<TableForDTProductCodePO> tableForDTProductCodePO)
{
if (tableForDTProductCodePO == null)
return BadRequest("Unusable resources.");
if (tableForDTProductCodePO.Count <= 0)
return BadRequest("Unusable resources.");
DataTable dtable = ToDataTable(tableForDTProductCodePO);
using (InspectionDBEntities dbCon = new InspectionDBEntities())
{
try
{
var response = dbCon.Database.SqlQuery<object>(
"exec dbo.InsertValueToTableForDTProductCodePO @TempTable",
dtable).ToString();
dbCon.SaveChanges();
return Ok("Done");
}
catch (Exception ex)
{
return BadRequest(ex.ToString());
}
}
}
以下是创建DataTable的方法:
public DataTable ToDataTable<TableForDTProductCodePO>(List<TableForDTProductCodePO> tableForDTProductCodePO)
{
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(TableForDTProductCodePO)); ;
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (TableForDTProductCodePO item in tableForDTProductCodePO)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
以下是存储过程代码:
ALTER PROCEDURE [dbo].[InsertValueToTableForDTProductCodePO]
@TempTable DTProductCodePO READONLY
AS
BEGIN
INSERT INTO TableForDTProductCodePO
SELECT *
FROM @TempTable
END
我没有收到任何错误,但数据未添加到数据库中。从Postman,我在控制器参数中得到正确的数据。
任何帮助?
谢谢