2

I am working on a ASP.net Core project. In that project, I need to execute an SQL string query and retrieve the result to a custom model. I tried to retrieve the query result using context.Database.SqlQuery<ReportModel>. But Database.SqlQuery is not supported in ASP.net Core. Please find my code given below:

        public List<ReportModel> GetReportDetails(string customQuery)
        {
            try
            {
                List<ReportModel> listReportModel = new List<ReportModel>();
                var queryResult = context.Database.SqlQuery<ReportModel>(customQuery);
                foreach (var item in queryResult)
                {
                    listReportModel.Add(item);
                }
                return listReportModel;
            }
            catch (Exception ex)
            {
                throw;
            }    
        }

I also tried with the following answer https://stackoverflow.com/questions/35631903/raw-sql-query-without-dbset-entity-framework-core But, using this solution I need to update my context class. I can't update my context class.

Is there any other way to execute the SQL string query in ASP.net Core 3.1? Any help would be appreciable. Thank You!

Vignesh VS
  • 921
  • 1
  • 14
  • 30

3 Answers3

1

You can use the code below.

var dataFromDB = context.ModelClass.FromSqlRaw("spName {0}", parameter).ToList();
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
1

In your comment, you said that you are getting an error:

Cannot create a DbSet for 'ReportModel' because this type is not included in the model for the context

The error simply is because the class you're using here ReportModel has apparently not been added to your context. You must write this:

public DbSet<ReportModel> ReportModel { get; set; }

When you write

var dataFromDB = context.ReportModel.FromSqlRaw("spName {0}", parameter).ToList();

you are querying it indirectly on the table. Hence It is not possible to execute query without modifying the context class. Context class becomes the helper to query your data from database.

Rohan Rao
  • 2,505
  • 3
  • 19
  • 39
1

You can use ADO.NET via the Context.Database property.

https://www.learnentityframeworkcore.com/raw-sql#leveraging-ado.net-via-the-context.database-property

And here is a concrete implementation.

https://github.com/dotnet/efcore/issues/2344#issuecomment-172641417

mj1313
  • 7,930
  • 2
  • 12
  • 32