3

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.

Alessio
  • 3,404
  • 19
  • 35
  • 48
Vignesh
  • 814
  • 7
  • 29
  • 1
    I think this link is helpful: [Raw SQL Query - Entity Framework Core](https://stackoverflow.com/questions/35631903/raw-sql-query-without-dbset-entity-framework-core) – hassan.ef Apr 12 '19 at 19:20
  • @hassan.ef Thank you so much for your help. I really appreciate it.It seems like it will work. I will implement and let you know once its done. Thanks again – Vignesh Apr 12 '19 at 19:37

1 Answers1

2

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

amirani
  • 260
  • 3
  • 9