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!

1
  • Look at my answer further down in then linked question Commented Jun 24, 2020 at 14:23

3 Answers 3

1

You can use the code below.

var dataFromDB = context.ModelClass.FromSqlRaw("spName {0}", parameter).ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

As i understand OP does not have ReportModel (or your ModelClass) set up in his context.
I tried this already. Actually, 'ReportModel' is a custom class and it is not in the context.
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.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.