2016-10-03 17 views
2

私はasp.netのコアアプリケーションのためにユーザーのログインを促そうとしています。 Microsoftのチュートリアルhereに従ってください。私は、学校関連のすべてのモデルを保存するためのSchoolContextと、アカウントモデル用のApplicationDbContextという2つのコンテキストを持っています。これはすべてsqliteデータベースに保存されます。
私のコンテキストにユーザーを登録しようとするまで、すべてうまく動作します。ユーザーを登録しようとすると、AspNetUsersテーブルエラーが見つかりません。私がデータベースを見ると、AspNetUserテーブルは表示されません。私はmigrationsを追加しようとしましたが、私はまだ同じエラーが発生します。なぜテーブルが作成されていないのですか?Asp.netコア - そのようなテーブルはありません:AspNetUsers

Startup.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); 
     } 
    } 
} 

ApplicationUser.cs

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

appsettings.json

エラー

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() 
+0

これが解決するかどうかわからない:http://stackoverflow.com/questions/22174212/entity-framework-6-with-sqlite-3-code-first-wont-create-tables –

+0

@SteveGreene私はそうは思わない、SchoolContextテーブルが開始されます。 – John

+0

[Users]テーブルが表示されますか?私の場合、1つのリクエストでUsersテーブルに書き込むこともできますが、次のリクエストでAspNetUsersから読み取ろうとします –

答えて

5

あなたはパッケージマネージャコンソールでupdate-databaseに電話をするのを忘れたようですね。これは実際に作成した移行を、接続しているデータベースに適用するものです。

その他の問題は、テーブル名をどのように更新したかにあります。マイグレーションを直接編集した場合、実行時に名前を変更したことを知る方法がなく、デフォルトの名前付きテーブルが検索されます。

ユーザテーブル名を変更するには、OnModelCreating方法であなたのDBのコンテキストでこのような何かをしたい:

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を実行して、再試行してください。

+1

データベースを削除してからデータベースを更新する必要がありました。ありがとう。 dotnet efデータベースの更新-c ApplicationDbContext – John

+0

申し訳ありませんがすぐに話しました。エラーは依然としてポップアップします。 – John

+0

これは私の問題かもしれません。おそらく、これがそうであるかどうかを確認するのに役立ちます。私は、移行テーブル名をAspNetUsersからContosoUsersに変更しました。 AspNetUsersがまだどこでも使用されているかどうかを調べるためにプロジェクトを検索しましたが、そうではありませんでした。だから、アイデンティティがContosoUsersの代わりにAspNetUsersを検索している理由はわかりません。 – John

関連する問題