Delen via


RelationalQueryableExtensions.FromSqlRaw<TEntity> Method

Definition

Creates a LINQ query based on a raw SQL query.

public static System.Linq.IQueryable<TEntity> FromSqlRaw<TEntity> (this Microsoft.EntityFrameworkCore.DbSet<TEntity> source, string sql, params object[] parameters) where TEntity : class;
public static System.Linq.IQueryable<TEntity> FromSqlRaw<TEntity> (this Microsoft.EntityFrameworkCore.DbSet<TEntity> source, string sql, params object?[] parameters) where TEntity : class;
static member FromSqlRaw : Microsoft.EntityFrameworkCore.DbSet<'Entity (requires 'Entity : null)> * string * obj[] -> System.Linq.IQueryable<'Entity (requires 'Entity : null)> (requires 'Entity : null)
<Extension()>
Public Function FromSqlRaw(Of TEntity As Class) (source As DbSet(Of TEntity), sql As String, ParamArray parameters As Object()) As IQueryable(Of TEntity)

Type Parameters

TEntity

The type of the elements of source.

Parameters

source
DbSet<TEntity>

An IQueryable<T> to use as the base of the raw SQL query (typically a DbSet<TEntity>).

sql
String

The raw SQL query.

parameters
Object[]

The values to be assigned to parameters.

Returns

IQueryable<TEntity>

An IQueryable<T> representing the raw SQL query.

Remarks

If the database provider supports composing on the supplied SQL, you can compose on top of the raw SQL query using LINQ operators: context.Blogs.FromSqlRaw("SELECT * FROM Blogs").OrderBy(b => b.Name).

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.

However, never pass a concatenated or interpolated string ($"") with non-validated user-provided values into this method. Doing so may expose your application to SQL injection attacks. To use the interpolated string syntax, consider using FromSql<TEntity>(DbSet<TEntity>, FormattableString) to create parameters.

This overload also accepts DbParameter instances as parameter values. In addition to using positional placeholders as above ({0}), you can also use named placeholders directly in the SQL query string.

See Executing raw SQL commands with EF Core for more information and examples.

Applies to