c# - Asp.net 核心 - 没有这样的表 : AspNetUsers

标签 c# entity-framework sqlite asp.net-core asp.net-identity

所以我正在尝试为我的 asp.net 核心应用程序实现用户登录。我正在关注微软教程 here .我有两个上下文,一个名为 SchoolContext 用于保存所有与学校相关的模型,另一个名为 ApplicationDbContext 用于保存帐户模型的上下文。这一切都被保存到 sqlite 数据库中。
一切正常,直到我尝试将用户注册到我的上下文中。当我尝试注册我得到的用户时,无法找到 AspNetUsers 表错误。如果我查看数据库,我看不到 AspNetUser 表。我尝试添加 migrations ,但我仍然遇到同样的错误。为什么没有创建表?

启动.cs

public class Startup {
        public IConfigurationRoot Configuration { get; }
        public Startup(IHostingEnvironment env) {
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {
            // Add Context services
            services.AddDbContext<SchoolContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("MainConnection")));
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlite(Configuration.GetConnectionString("MainConnection")));

            // Add Identify servies 
            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();
            // Add framework services
            services.AddMvc();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SchoolContext context) {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            // Config hot module replacement
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
                app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                    HotModuleReplacement = true
                });
            }
            else {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();
            // Enabled Identity
            app.UseIdentity();
            // Confgure routes 
            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");

                routes.MapSpaFallbackRoute(
                    name: "spa-fallback",
                    defaults: new { controller = "Home", action = "Index" });
            });
            // Initialize school database [FOR TESTING] 
            DbInitializer.Initialize(context);
        }
    }

ApplicationDbContext.cs

namespace ContosoUniversity.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options)
        {
        }

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

应用程序用户.cs

namespace ContosoUniversity.Models
{
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser
    {
    }
}

应用设置.json

  "ConnectionStrings": {
    "MainConnection": "Data Source=/home/Josn/AspNetCore/ContosoUniversity/Databases/database.db"
  },

错误

fail: Microsoft.EntityFrameworkCore.Query.RelationalQueryCompilationContextFactory[1]
      An exception occurred in the database while iterating the results of a query.
      Microsoft.Data.Sqlite.SqliteException: SQLite Error 1: 'no such table: AspNetUsers'.
         at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc, Sqlite3Handle db)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
         at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReaderAsync(CommandBehavior behavior, CancellationToken cancellationToken)
         at Microsoft.Data.Sqlite.SqliteCommand.<ExecuteDbDataReaderAsync>d__53.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.<ExecuteAsync>d__20.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable.AsyncEnumerator.<MoveNext>d__8.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.<_FirstOrDefault>d__82`1.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.TaskResultAsyncEnumerable`1.Enumerator.<MoveNext>d__3.MoveNext()
      --- End of stack trace from previous location where exception was thrown ---
         at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
         at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
         at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()

最佳答案

听起来您好像忘了在程序包管理器控制台中调用 update-database。这就是将您创建的迁移实际应用到连​​接的数据库的原因。

另一个问题可能与您更新表名的方式有关。如果您直接编辑迁移,它无法知道您在运行时更改了名称,并且仍会查找默认的命名表。

要更改用户表名称,您想在 OnModelCreating 方法中的数据库上下文中执行类似的操作:

protected override void OnModelCreating( ModelBuilder builder ) {
    base.OnModelCreating( builder );
    // Customize the ASP.NET Identity model and override the defaults if needed.
    // For example, you can rename the ASP.NET Identity table names and more.
    // Add your customizations after calling base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>() //Use your application user class here
           .ToTable( "ContosoUsers" ); //Set the table name here
}

然后您需要创建迁移以确保通过在程序包管理器控制台中运行以下命令来更新所有内容:

add-migration RenamedUserTable

然后快速运行 update-database 并重试。

关于c# - Asp.net 核心 - 没有这样的表 : AspNetUsers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39835241/

相关文章:

c# - 使用 Entity Framework Code First 创建文本列

c# - 密码登录异步 MVC C#

.net - 无法保存 Entity Framework 继承的类型

java - 新建的 SQLitedatabase 表不存在

iOS - 如何在多线程中正确执行sqlite3写入操作?

c# - Fluent NHibernate 生成的列名别名太长

c# - Thread.Sleep(2500) 与 Task.Delay(2500).Wait()

c# - Entity Framework /LINQ to SQL 数据绑定(bind)是否使用反射?

android - 如何将数据从sqlite存储到google excel表

c# - HTTPs 客户端在 Azure Web App 上连接到没有可信链(非可信 CA)的服务器