Search code examples
c#asp.net-core-mvc

How to implement Raw SQL without model in ASP.NET Core MVC?


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.


Solution

  • 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.