Database.SqlQuery Method (Type, String, Object)
Creates a raw SQL query that will return elements of the given type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type. Use the SqlQuery(String, Object) method to return entities that are tracked by the context. As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection attack. You can include parameter place holders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter. context.Database.SqlQuery(typeof(Post), "SELECT * FROM dbo.Posts WHERE Author = @p0", userSuppliedAuthor); Alternatively, you can also construct a DbParameter and supply it to SqlQuery. This allows you to use named parameters in the SQL query string. context.Database.SqlQuery(typeof(Post), "SELECT * FROM dbo.Posts WHERE Author = @author", new SqlParameter("@author", userSuppliedAuthor));
Assembly: EntityFramework (in EntityFramework.dll)
public function SqlQuery( elementType : Type, sql : String, ... parameters : Object ) : DbRawSqlQuery
- Type: System.Type
The type of object returned by the query.
- Type: System.String
The SQL query string.
- Type: System.Object
The parameters to apply to the SQL query string. If output parameters are used, their values will not be available until the results have been read completely. This is due to the underlying behavior of DbDataReader, see http://go.microsoft.com/fwlink/?LinkID=398589 for more details.