在C#中使用datatable参数执行存储过程时出错

时间:2018-07-31 07:11:11

标签: c# sql sql-server stored-procedures

我正在尝试创建一个存储过程,以添加或更新在c#中执行的对象的集合,但是不确定为什么它无法在c#中正确执行,而在sql中可以正常工作。

我不确定如何生成一些有用的错误消息来帮助调试。

任何向我指引正确方向的技巧或指针,将不胜感激。

这是示例代码:

SQL脚本:

CREATE TYPE CodeList
AS TABLE
(
    Code varchar(255) NOT NULL UNIQUE,
    Name varchar(max) NOT NULL,
    GeneratedDate date NULL
);
GO

PRINT 'Created CodeList Type';
GO

CREATE PROCEDURE AddOrUpdateCodes
    @List AS CodeList READONLY
AS
BEGIN
    SET NOCOUNT ON;

    MERGE dbo.Code AS tgt
    USING @List AS src
    ON tgt.Code = src.Code
    WHEN MATCHED THEN
        UPDATE SET Name = src.Name, GeneratedDate = src.GeneratedDate
    WHEN NOT MATCHED THEN
        INSERT (Code, Name, GeneratedDate) VALUES (src.Code, src.Name, src.GeneratedDate);
END
GO

PRINT 'Created AddOrUpdateCodes Stored Procedure';
GO

DECLARE @List AS CodeList;

INSERT INTO @List (Code, Name, GeneratedDate) VALUES ('SQLTEST', 'SQLTEST', '2018-07-30')

EXEC AddOrUpdateCodes @List
GO

SELECT * FROM Symbol;

C#代码:

public int AddOrUpdateCodes(List<Code> codes)
{
    using (var entity = new CodeEntities())
    {
        var dataTable = new DataTable("CodeList");
        using (var reader = ObjectReader.Create(codes, "Code", "Name", "GeneratedDate"))
        {
            dataTable.Load(reader);
        }

        var sqlParameter = new SqlParameter("@List", dataTable);
        sqlParameter.SqlDbType = SqlDbType.Structured;
        sqlParameter.TypeName = "dbo.CodeList";
        var result = entity.Database.ExecuteSqlCommand("AddOrUpdateCodes",
            sqlParameter);
        entity.SaveChanges();
        return result;
    }
}

1 个答案:

答案 0 :(得分:2)

DbContext.Database.ExecuteSqlCommand()方法有助于对数据库执行给定的DDL / DML命令。尝试使用此行传递SqlParameters:

var result = entity.Database.ExecuteSqlCommand("AddOrUpdateCodes @List",
    sqlParameter);
    entity.SaveChanges();
        return result;