Categories
entity-framework sql sql-injection

When using DbSet.SqlQuery(), how to use named parameters?

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");

Is there a way to use named parameters with the Entity Framework DbSqlQuery class?