Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Adding Identity - Cannot create a DbSet for 'ApplicationRole' because this type is not included in the model for the context.

$
0
0

I am trying to create an ASP.NET Core application from scratch. It helps to understand everything.  Unfortunately, I am getting an error when I attempt to see my database.  The error is shown below.  I have read through everything it seems like.  I have googled.  I have tried a bunch of different things.  I am completely lost on this and I admit it.  I am trying to create some roles and to create a couple of users so that I can easily seed my database.  Can someone show me a correct/recommended way to add some roles and a user to my starting app?

+ $exception {System.InvalidOperationException: Cannot create a DbSet for 'ApplicationRole' because this type is not included in the model for the context.
The exception occurs on this command in my DbInitializer Initilize() method:

!(await _roleManager.RoleExistsAsync("Administrator"))

Here is the content of my Startup class:

public class Startup
{
public static IConfigurationRoot Configuration { get; set; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{

var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");

Configuration = builder.Build();

services.AddSingleton(Configuration);

// Add EF services to the services container.
services.AddDbContext<PoopTheWorldContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("PoopConnection")));

services.AddMvcCore();

services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<PoopTheWorldContext>()
.AddDefaultTokenProviders();

services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = false;
options.Password.RequiredUniqueChars = 6;

// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Lockout.AllowedForNewUsers = true;

// User settings
options.User.RequireUniqueEmail = true;
});

services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.Cookie.Expiration = TimeSpan.FromDays(150);
options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
});

// Add Database Initializer
services.AddScoped<IDbInitializer, DbInitializer>();

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, IDbInitializer dbInitializer)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});

app.UseStaticFiles();

app.UseAuthentication();

dbInitializer.Initialize();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}

Here is the content of my DbInitializer class:

public class DbInitializer : IDbInitializer
{
private readonly PoopTheWorldContext _context;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<ApplicationRole> _roleManager;

public DbInitializer(
PoopTheWorldContext context,
UserManager<ApplicationUser> userManager,
RoleManager<ApplicationRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}

//This example just creates an Administrator role and one Admin users
public async void Initialize()
{
//create database schema if none exists
_context.Database.EnsureCreated();

//If there is already an Administrator role, abort
if (!(await _roleManager.RoleExistsAsync("Administrator")))  <- Error occurs here
{
//Create the Administartor Role
await _roleManager.CreateAsync(new ApplicationRole("Administrator"));
}

//Create the default Admin account and apply the Administrator role
string user = "xxx@yyy.com";
string password = "AbC!12345";
var success = await _userManager.CreateAsync(new ApplicationUser { UserName = user, Email = user, EmailConfirmed = true }, password);
if (success.Succeeded)
{
await _userManager.AddToRoleAsync(await _userManager.FindByNameAsync(user), "Administrator");
}
}

Thanks for any help.  :-)


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>