AJ_*_*AJ_ 3 c# sqlite entity-framework asp.net-identity asp.net-core
所以我试图为我的asp.net核心应用程序实现用户登录.我在这里关注微软教程.我有两个上下文,一个叫做SchoolContext,用于保存所有与学校相关的模型,另一个叫做ApplicationDbContext,用于Account模型.这都被保存到sqlite数据库.
一切正常,直到我尝试将用户注册到我的上下文.当我尝试注册我得到的用户时,无法找到AspNetUsers表错误.如果我查看数据库,我没有看到AspNetUser表.我尝试添加迁移,但我仍然得到同样的错误.为什么没有创建表?
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);
}
}
Run Code Online (Sandbox Code Playgroud)
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
ApplicationUser.cs
namespace ContosoUniversity.Models
{
// Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
}
}
Run Code Online (Sandbox Code Playgroud)
appsettings.json
"ConnectionStrings": {
"MainConnection": "Data Source=/home/Josn/AspNetCore/ContosoUniversity/Databases/database.db"
},
Run Code Online (Sandbox Code Playgroud)
错误
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()
Run Code Online (Sandbox Code Playgroud)
听起来你忘了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
}
Run Code Online (Sandbox Code Playgroud)
然后,您需要创建一个迁移,以确保通过在包管理器控制台中运行以下内容来更新所有内容:
add-migration RenamedUserTable
然后快速运行update-database并再试一次.
| 归档时间: |
|
| 查看次数: |
3774 次 |
| 最近记录: |