ASP.NET MVC with EF Core 6
When I tried to set up a new ASP.NET MVC project with Entity Framework Core 6, I ran into some problems until I got the database to work. When I finally had success, I decided that I would share my code. "Api_Entities" is the name of the class that defines the database context. "User" is the name of a table in the database.
public partial class Api_Entities : DbContext
{
public string sqlConnectionString = <your connection string>;
public Api_Entities(DbContextOptions<Api_Entities> options) : base(options)
{ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(sqlConnectionString, builder => builder.EnableRetryOnFailure());
}
}
In Startup.cs:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<Api_Entities>(options => options.UseSqlServer(Configuration.GetConnectionString("Api_Entities")));
}
In AccountController.cs:
public class AccountController : Controller
{
private readonly Api_Entities db;
private UserManager<User, int> userManager;
public AccountController(Api_Entities db)
{
this.db = db;
this.userManager = new UserManager<User, int>(new UserStoreBehavior(db));
}
Kommentare
Kommentar veröffentlichen