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?
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.
EF builds and executes a parameterized query in the database if the LINQ-to-Entities query uses parameters, such as below.
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.
We can use SQLQuery() method to write SQL queries which return an entity object. Example: //DbContext.
var param = new ObjectParameter(":p0", "Bob");
MyRepository.Users.SqlQuery("Select * from Users where Name = :p0", param);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With