1

In ASP.NET Core 5 MVC, I have:

dbContext = mfdDbContext

var myquery = select * from teachers order by id desc

The normal convention is this:

var results = mfdDbContext.SomeModel
                          .FromSqlRaw("select id, firstName, lastName from teachers order by id desc")
                          .ToList();

But I don't have a model class.

How do I implement the above raw query without a model? Then generate my own model.

3
  • Don't use Entity Framework for that query? Commented Nov 8, 2021 at 12:35
  • @gunr2171 - What do I do? Commented Nov 8, 2021 at 12:37
  • Does this answer your question? Raw SQL Query without DbSet - Entity Framework Core Commented Nov 8, 2021 at 12:39

1 Answer 1

2

You cannot achieve this with EF. You have to have model class anyway. That's why EF is so powerful.

Instead, you could use Dapper https://dapper-tutorial.net/query

string sql = "select * from teachers order by id desc";

using (var connection = new SqlConnection(connectionString))
{    
    var data = connection.Query(sql).ToList();

    // use data
}

but anyway, you have manually to get the columns. I would recommend to have a DB Model registered with EF, it will make your life easier.

Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to bring in the DbContext here using (var connection = new SqlConnection(connectionString)) instead of the Connection string? Since I have this inside DBContext private readonly string Conn ="Server=myserver;Database=myDB;User Id=myuser;Password=mypw;";
@midowu i think you can try _dbContext.Database.GetDbConnection().ConnectionString
Do you mean I replace using (var connection = new SqlConnection(connectionString)) with _dbContext.Database.GetDbConnection().ConnectionString
@midowu use this using (var connection = new SqlConnection(mfdDbContext.Database.GetDbConnection().ConnectionString))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.