我将用户定义的表类型传递给存储过程。但它会抛出错误,因为“从对象类型System.Collections.Generic.List`1到已知的托管提供程序本机类型不存在映射。”
UserDefinedTableType:
CREATE TYPE UserQueryAttachmentList AS TABLE
(
[UserQueryId] NVARCHAR(50),
[AttachmentPath] NVARCHAR(200),
[AttachmentName] NVARCHAR(200),
[AttachmentFor] NVARCHAR(50),
[CreatedBy] NVARCHAR(50)
);
Stored Procedure:
CREATE PROCEDURE PROC_UserQueryAttachment_Insert
(
@Table UserQueryAttachmentList READONLY
)
AS
BEGIN
INSERT INTO dbo.[UserQueryAttachments]
(
UserQueryId,
AttachmentPath,
AttachmentName,
AttachmentFor,
CreatedBy,
CreatedDate
)
SELECT
UserQueryId,
AttachmentPath,
AttachmentName,
AttachmentFor,
CreatedBy,
GETDATE()
FROM
@Table T
END
C#:
public override bool SaveUserQueryAttachment(List<UserQueryAttachmentToCreate> fileList)
{
try
{
this.ExecuteStoredProcedureOrQuery<UserQueryAttachmentToCreate>("PROC_UserQueryAttachment_Insert", CommandType.StoredProcedure,
new SqlParameter("@Table", fileList)
);
return true;
}
catch (Exception ex)
{
return false;
}
}
请指导我这个错误发生的原因?
答案 0 :(得分:1)
对象列表无法直接传递给SQL Server。尝试传递这样的DataTable(代码未选中):
public override bool SaveUserQueryAttachment(List<UserQueryAttachmentToCreate> fileList)
{
// TODO: open a SQL connection here
using (SqlCommand cmd = new SqlCommand("exec PROC_UserQueryAttachment_Insert @table", connection))
{
using (var table = new DataTable())
{
table.Columns.Add("UserQueryId", typeof(string));
table.Columns.Add("AttachmentPath", typeof(string));
table.Columns.Add("AttachmentName", typeof(string));
table.Columns.Add("AttachmentFor", typeof(string));
table.Columns.Add("CreatedBy", typeof(string));
table.Rows.Add(fileList.ToArray());
var list = new SqlParameter("@table", SqlDbType.Structured);
list.TypeName = "dbo.UserQueryAttachmentList";
list.Value = table;
cmd.Parameters.Add(list);
cmd.ExecuteReader();
}
}
// TODO: close the SQL connection
}