Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I connect to database in ASP.NET Core Web API without using EF?

I am attempting to create an ASP.NET Core Web API without using EF Core. Instead, I would like to use System.Data.SQLClient to connect to SQL server, and query it using plain old SQL. That said, I'm having a bit of trouble figuring out how to establish the connection. I've found a lot of tutorials online that address how to do this with EF. But, I'm a bit perplexed as to how it's done without it.

like image 326
toolshed Avatar asked Mar 01 '26 11:03

toolshed


1 Answers

You do it exactly the same way as you would in any .net application:

using (var conn = new System.Data.SqlClient.SqlConnection(connectionString)) {
    conn.Open();
    using (var cmd = conn.CreateCommand()) {
        cmd.CommandText = "SELECT 'hello world'";
        using (var reader = cmd.ExecuteReader()) {
            while (reader.Read()) {
                ...
            }
        }
    }
}

You will find that some parts of asp.net core require EF, like the identity claims stuff, so you will need to handle your own authentication and won't be able to use their security attributes and the like. I've gone this route on several asp.net core projects with no regrets

like image 99
Tim Avatar answered Mar 03 '26 00:03

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!