当使用DbSet< T> .SqlQuery()时,如何使用命名参数? [英] When using DbSet<T>.SqlQuery(), how to use named parameters?
问题描述
我是使用命名参数而不是基于字符串的参数注入的大粉丝。对于大多数形式的SQL注入,它是类型安全和安全的。在旧的ADO.NET中,我将为我的查询创建一个SqlCommand对象和一堆SqlParameters。
I'm a big fan of using named parameters instead of string-based parameter injection. It's type-safe and safe against most forms of SQL injection. In old ADO.NET, I would create a SqlCommand object and a bunch of SqlParameters for my query.
var sSQL = "select * from Users where Name = @Name";
var cmd = new SqlCommand(conn, sSQL);
cmd.Parameters.AddWithValue("@Name", "Bob");
cmd.ExecuteReader();
现在,在实体框架中,它显示(在此链接上)已经回归到一个简单的字符串。格式语句和字符串注入:(简化为讨论)
Now, in Entity Framework, it appears (on this link) to have regressed to a simple String.Format statement and string injection again: (simplified for discussion)
MyRepository.Users.SqlQuery("Select * from Users where Name = {0}", "Bob");
有没有办法在Entity Framework DbSqlQuery类中使用命名参数?
Is there a way to use named parameters with the Entity Framework DbSqlQuery class?
推荐答案
var param = new ObjectParameter(":p0", "Bob");
MyRepository.Users.SqlQuery("Select * from Users where Name = :p0", param);
这篇关于当使用DbSet< T> .SqlQuery()时,如何使用命名参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!