C # Asp.net MVC Невозможно создать DbSet для «IdentityUser», поскольку этот тип не включен в модель для контекста.) - PullRequest
0 голосов
/ 25 октября 2018

Я пытаюсь установить идентификатор администратора для моего проекта.Я решил сделать это в программе startup.cs.Я добавил начальный метод CreateUsersAndRoles в startup.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using sbingP3.Data;
using sbingP3.Models;
using sbingP3.Services;
using Microsoft.AspNetCore.Mvc;

namespace sbingP3
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //Core 2.1
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddDefaultUI()
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            // Add application services.
            services.AddTransient<IEmailSender, EmailSender>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); ;
        }

        private async Task CreateUsersAndRoles(IServiceProvider serviceProvider)
        {
            //Get reference to RoleManager and UserManager from serviceProvider through dependency injection
            var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var UserManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();

            //Check if admin role exists and if not add it.
            var roleExist = await RoleManager.RoleExistsAsync("Admin");
            if (!roleExist)
            {
                //create the roles and seed them to the database: Question 1  
                await RoleManager.CreateAsync(new IdentityRole("Admin"));
            }

            //Check if admin user exists and if not add it
            IdentityUser user = await UserManager.FindByEmailAsync("admin@aserver.net");

            if (user == null)
            {
                user = new IdentityUser()
                {
                    UserName = "admin@aserver.net",
                    Email = "admin@aserver.net",
                };
                await UserManager.CreateAsync(user, "Password1!");

                //Add user to admin role
                await UserManager.AddToRoleAsync(user, "Admin");
            }
        }


        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
        {
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();

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

            CreateUsersAndRoles(serviceProvider).Wait();
        }
    }
}

Я отладил программу, и ошибка возникает в следующей строке в моем методе seed:

Этот идентичный код успешно выполняется в другом проекте на той же машине, поэтому я решил, чтоэто может быть связано с моими спецификациями проекта.Я пробовал разные версии файла csproj, но все они приводили к одной и той же ошибке.

Я использую ASP.NET Core 2.1.

вот мой * .csproj файл:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <UserSecretsId></UserSecretsId>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="bootstrap" Version="4.1.3" />
    <PackageReference Include="bootstrap.sass" Version="4.1.3" />
    <PackageReference Include="MailKit" Version="2.0.6" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.5" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.1.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.4" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.5" />
  </ItemGroup>

</Project>

Ответы [ 2 ]

0 голосов
/ 28 октября 2018

Попробуйте использовать это приложение DBContext.это может решить вашу проблему.

public class ApplicationDbContext : IdentityDbContext<IdentityUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }

}
0 голосов
/ 28 октября 2018

Как выглядит ваш класс ApplicationDbContext?

public class ApplicationDbContext : IdentityDbContext<IdentityUser>

также, возможно, вы можете попробовать отредактировать файл запуска с помощью этого?

services.AddDefaultIdentity<ApplicationUser>()
...