【问题标题】:UDT Type in Stored Procedure: Error - No mapping exists from object type System.Collections.Generic.List`1 to a known managed provider native type存储过程中的 UDT 类型:错误 - 不存在从对象类型 System.Collections.Generic.List`1 到已知托管提供程序本机类型的映射
【发布时间】:2017-03-29 09:47:56
【问题描述】:

我将用户定义的表类型传递给存储过程。但它会引发错误,因为“不存在从对象类型 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;
        }
    }

请指导我为什么会出现这个错误?

【问题讨论】:

  • 您需要将 DataTable 发送到存储过程,而不是 List。

标签: c# sql-server asp.net-mvc stored-procedures user-defined-types


【解决方案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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多