如何将参数传递给 DbContext.Database.ExecuteSqlCommand 方法? [英] How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

查看:29
本文介绍了如何将参数传递给 DbContext.Database.ExecuteSqlCommand 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我确实需要在实体框架中直接执行 sql 命令.我无法弄清楚如何在我的 sql 语句中使用参数.以下示例(不是我的真实示例)不起作用.

Let's just suppose I have a valid need for directly executing a sql command in Entity Framework. I am having trouble figuring out how to use parameters in my sql statement. The following example (not my real example) doesn't work.

var firstName = "John";
var id = 12;
var sql = @"Update [User] SET FirstName = @FirstName WHERE Id = @Id";
ctx.Database.ExecuteSqlCommand(sql, firstName, id);

ExecuteSqlCommand 方法不允许您像在 ADO.Net 和 此方法的文档 没有给出关于如何执行参数化查询的任何示例.

The ExecuteSqlCommand method doesn't allow you to pass in named parameters like in ADO.Net and the documentation for this method doesn't give any examples on how to execute a parameterized query.

如何正确指定参数?

推荐答案

事实证明这是有效的.

var firstName = "John";
var id = 12;
var sql = "Update [User] SET FirstName = {0} WHERE Id = {1}";
ctx.Database.ExecuteSqlCommand(sql, firstName, id);

这篇关于如何将参数传递给 DbContext.Database.ExecuteSqlCommand 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆