0

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.

Thanks

midowu
  • 937
  • 5
  • 19
  • 40

1 Answers1

1

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.

Maxian Nicu
  • 2,166
  • 3
  • 17
  • 31
  • 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 Nov 08 '21 at 14:10
  • @midowu i think you can try `_dbContext.Database.GetDbConnection().ConnectionString` – Maxian Nicu Nov 08 '21 at 14:30
  • Do you mean I replace using (var connection = new SqlConnection(connectionString)) with _dbContext.Database.GetDbConnection().ConnectionString – midowu Nov 08 '21 at 14:32
  • @midowu use this `using (var connection = new SqlConnection(mfdDbContext.Database.GetDbConnection().ConnectionString))` – Maxian Nicu Nov 08 '21 at 15:00