How to set database connection in ASP NET

Jack Herer 110 Reputation points
2023-04-23T18:51:35.6266667+00:00
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{          

optionsBuilder.UseMySQL("server=YOURSERVER;database=YOURDATABASE;user=YOURUSERNAME;password=YOURPASSWORD;SslMode=none");

}
Developer technologies ASP.NET ASP.NET Core
{count} votes

1 answer

Sort by: Most helpful
  1. Anonymous
    2023-04-24T06:05:25.2633333+00:00

    Hi @Jack Herer

    How to set database connection in ASP NET

    Your code is correct. You can set the database connection using the UseMySQL method and in the DbContext's OnConfiguring method. Then, in the Program.cs (asp.net 6+) /Startup.cs (asp.net core 3.1) fille, register the dbcontext using the AddDbContext method like this:

    builder.Services.AddDbContext<{your Db context}>();
    

    After that you can inject the DbContext in the controller or razor page and use it to access data from database.
    Besides, you can also store the connection string in the appsettings.json file, and set the connection string in the program.cs/startup.cs file. like this:
    appsettings.json file:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "ConnectionStrings": {
        "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=TestDb;Trusted_Connection=True;MultipleActiveResultSets=true"
      },
      "AllowedHosts": "*"
    }
    

    The DbContext :

        public class TestDbContext:DbContext
        {
            public DbSet<Movie> Movies { get; set; }
            public TestDbContext(DbContextOptions<TestDbContext> options)
            : base(options)
            {
    
            }  
        }
    

    Then, in the program.cs file (it is an Asp.net 6 MVC application), register the DbContext and set the connection string,

    // Add services to the container.
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
    builder.Services.AddDbContext<TestDbContext>(options => options.UseSqlServer(connectionString));
    

    After that, you can enable migration, and then inject the dbcontext in the controller/razor page. Like this:

        public class HomeController : Controller
        {
            private readonly TestDbContext _dbcontext;
    
            public HomeController(TestDbContext testDbContext)
            {
                _dbcontext=testDbContext;
            }
            public IActionResult Index()
            {
                var result = _dbcontext.Movies.ToList();
                return View();
            }
        }
    

    More detail information, refer to the following articles:
    Creating a Database with Code First in EF Core

    Part 5, work with a database in an ASP.NET Core MVC app
    Use Entity Framework Core 5.0 In .NET Core 3.1 With MySQL Database


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
    Best regards,
    Dillion

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.