6

I am new to .NET Core. I have defined the connection string in appsettings.json like this:

"ConnectionStrings": {
    "TestBD": "Server=localhost;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}

I am not using Entity Framework. I need to connect to the database using this connection string from the Program.cs file.

Any help is really appreciated. Thanks

1
  • 2
    You can use the SqlConnection, SqlCommand etc. classes from ADO.NET in .NET 6 - no problem. There are tons of resources showing you how to do this exactly. Make use of the Microsoft.Data.SqlClient nuget package - see this article as a starting point Commented Feb 25, 2022 at 5:10

1 Answer 1

8

You refer the following sample code to use ADO.NET in Asp.net 6 program.cs:

//required using Microsoft.Data.SqlClient;
app.MapGet("/movies", () =>
{
    var movies = new List<Movie>();
    //to get the connection string 
    var _config = app.Services.GetRequiredService<IConfiguration>();
    var connectionstring = _config.GetConnectionString("DefaultConnection");
    //build the sqlconnection and execute the sql command
    using (SqlConnection conn = new SqlConnection(connectionstring))
    {
        conn.Open();  
        string commandtext = "select MovieId, Title, Genre from Movie";

        SqlCommand cmd = new SqlCommand(commandtext, conn); 

        var reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            var movie = new Movie()
            {
                MovieId = Convert.ToInt32(reader["MovieId"]),
                Title = reader["Title"].ToString(),
                Genre = reader["Genre"].ToString()
            };

            movies.Add(movie);
        } 
    }
    return movies;
});

The result like this:

enter image description here

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

Comments

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.