Database.SqlQuery Method (Type, String, Object[])

[This page is specific to the Entity Framework version 6. The latest version is available as the 'Entity Framework' NuGet package. For more information about Entity Framework, see msdn.com/data/ef.]

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

Namespace:  System.Data.Entity
Assembly:  EntityFramework (in EntityFramework.dll)

Syntax

'Declaration
Public Function SqlQuery ( _
    elementType As Type, _
    sql As String, _
    ParamArray parameters As Object() _
) As DbRawSqlQuery
'Usage
Dim instance As Database 
Dim elementType As Type 
Dim sql As String 
Dim parameters As Object()
Dim returnValue As DbRawSqlQuery 

returnValue = instance.SqlQuery(elementType, _
    sql, parameters)
public DbRawSqlQuery SqlQuery(
    Type elementType,
    string sql,
    params Object[] parameters
)
public:
DbRawSqlQuery^ SqlQuery(
    Type^ elementType, 
    String^ sql, 
    ... array<Object^>^ parameters
)
member SqlQuery : 
        elementType:Type * 
        sql:string * 
        parameters:Object[] -> DbRawSqlQuery
public function SqlQuery(
    elementType : Type, 
    sql : String, 
    ... parameters : Object[]
) : DbRawSqlQuery

Parameters

  • elementType
    Type: System.Type
    The type of object returned by the query.
  • parameters
    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 https://go.microsoft.com/fwlink/?LinkID=398589 for more details.

Return Value

Type: System.Data.Entity.Infrastructure.DbRawSqlQuery
A DbRawSqlQuery object that will execute the query when it is enumerated.

See Also

Reference

Database Class

SqlQuery Overload

System.Data.Entity Namespace