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