Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using DbSet<T>.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?

like image 955
Eric Falsken Avatar asked Oct 17 '12 00:10

Eric Falsken


People also ask

What are named parameters in SQL?

Such parameters are called named parameters. ODBC supports the use of named parameters. In ODBC, named parameters are used only in calls to stored procedures and cannot be used in other SQL statements. The driver checks the value of the SQL_DESC_UNNAMED field of the IPD to determine whether named parameters are used.

Does Entity Framework use parameterized queries?

EF builds and executes a parameterized query in the database if the LINQ-to-Entities query uses parameters, such as below.

How do I use ExecuteSqlRaw?

ExecuteSqlRaw(DatabaseFacade, String, IEnumerable<Object>) Executes the given SQL against the database and returns the number of rows affected. Note that this method does not start a transaction. To use this method with a transaction, first call BeginTransaction(DatabaseFacade, IsolationLevel) or UseTransaction.

Which method is used to retrieve data using SQL query statements in EF?

We can use SQLQuery() method to write SQL queries which return an entity object. Example: //DbContext.


1 Answers

var param = new ObjectParameter(":p0", "Bob");
MyRepository.Users.SqlQuery("Select * from Users where Name = :p0", param);
like image 54
gdoron is supporting Monica Avatar answered Oct 28 '22 19:10

gdoron is supporting Monica