RelationalQueryableExtensions.FromSqlRaw<TEntity>(DbSet<TEntity>, String, Object[]) Method

Definition

Creates a LINQ query based on a raw SQL query.

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 dbo.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:

context.Blogs.FromSqlRaw("SELECT * FROM [dbo].[SearchBlogs]({0})", userSuppliedSearchTerm)

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 FromSqlInterpolated<TEntity>(DbSet<TEntity>, FormattableString) to create parameters.

This overload also accepts DbParameter instances as parameter values. This allows you to use named parameters in the SQL query string:

context.Blogs.FromSqlRaw("SELECT * FROM [dbo].[SearchBlogs]({@searchTerm})", new SqlParameter("@searchTerm", userSuppliedSearchTerm))
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.

Applies to