EF Core ExecuteSqlCommand和参数

时间:2017-07-31 13:21:10

标签: c# entity-framework asp.net-core entity-framework-core

我必须在ef core 1.1.2上执行sql命令:

 var projectParam = new SqlParameter("@projectid", SqlDbType.UniqueIdentifier).Value = inventory.ProjectId;
 var locationParam = new SqlParameter("@locationid", SqlDbType.UniqueIdentifier).Value = location.Id;
 var scanOrderParam = new SqlParameter("@scanorder", SqlDbType.Int).Value = scanOrder;
 _ctx.Database.ExecuteSqlCommand("update Inventories set ScanOrder=ScanOrder+1 where ProjectId = '@projectid' AND LocationId = '@locationid' AND ScanOrder>'@scanorder';",
                  parameters: new[] {
                                     projectParam, locationParam, scanOrderParam
                  });

抛出异常:

  • 发生了未处理的异常:从字符串转换为uniqueidentifier时转换失败。
  • 如果我在命令中写入ScanOrder> @scanorder,则表示必须声明scanorder参数。哪个是int。
  • 如果我不在projectid和locationid使用撇号,则抛出异常参数必须声明。

在ef core中使用参数的正确方法是什么?

编辑(解决方案): 问题是我声明参数并给它们值的方式。如果我使用这个表格,它可以工作:

var projectParam = new SqlParameter("@projectid", SqlDbType.UniqueIdentifier);
projectParam.Value = inventory.ProjectId;
var locationParam = new SqlParameter("@locationid", SqlDbType.UniqueIdentifier);
locationParam.Value = location.Id;
var scanOrderParam = new SqlParameter("@scanorder", SqlDbType.Int);
scanOrderParam.Value = scanOrder;

1 个答案:

答案 0 :(得分:1)

 var queryItem = new SqlParameter("@table", SqlDbType.Char) {Value = yourValue};