我正在尝试创建一个存储过程来添加或更新在 c# 中执行的对象集合,但不确定为什么它在 c# 中无法正确执行而在 sql 中运行良好。我不确定如何生成一些有用的错误消息来帮助调试。任何指导我走向正确方向的提示或指针都非常感谢。这是示例代码:SQL 脚本:CREATE TYPE CodeListAS TABLE( Code varchar(255) NOT NULL UNIQUE, Name varchar(max) NOT NULL, GeneratedDate date NULL);GOPRINT 'Created CodeList Type';GOCREATE PROCEDURE AddOrUpdateCodes @List AS CodeList READONLYASBEGIN 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);ENDGOPRINT 'Created AddOrUpdateCodes Stored Procedure';GODECLARE @List AS CodeList;INSERT INTO @List (Code, Name, GeneratedDate) VALUES ('SQLTEST', 'SQLTEST', '2018-07-30')EXEC AddOrUpdateCodes @ListGOSELECT * 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 回答
九州编程
TA贡献1785条经验 获得超4个赞
DbContext.Database.ExecuteSqlCommand() 方法有助于对数据库执行给定的 DDL/DML 命令。尝试使用这一行传递 SqlParameters:
var result = entity.Database.ExecuteSqlCommand("AddOrUpdateCodes @List",
sqlParameter);
entity.SaveChanges();
return result;
- 1 回答
- 0 关注
- 219 浏览
添加回答
举报
0/150
提交
取消