Search code examples
c#asp.net-core-2.0entity-framework-core-2.1

How to run the Raw SQL query using EntityFrameworkCore and map the result to the type IEnumerable<T>?


I am new to EntityFramework core. I am moving our existing .net framework4.6.1 application to .net core 2. In EntityFramework 6, we are able to run raw SQL query and we are able to get the values mapped to the type (T) using below code.

public IEnumerable<T> ExecuteSQL<T>(string sql)
{
   return Context.Database.SqlQuery<T>(sql, new object[] { });
}

But, EFcore does not support this. I wanted to run the Raw SQL query using EntityFrameworkCore and I should be able to map the result in IEnumerable . It seems like SqlQuery is not present in EFCore. Please help me to find the alternative way to achieve the functionality. . Thanks in advance.

Note: here, T will not be a DbSet Class.it will be a ViewModel which has combination of fields from multiple tables.


Solution

  • According to Entity framework core documentation you can use Query().FromSql(sql) method.

    public IEnumerable<T> ExecuteSQL<T>(string sql) where T : class
        {
            return context.Query<T>().FromSql(sql).ToList();
        }
    

    More details Explained here