我正在使用 ASP.NET Identity Sample来自 Asp 团队,我正在尝试更改 IdentityDbContext
...
我用构造函数试过了
public MyDbContext() : base("MyConnectionString") { } // base is IdentityDbContext
类似于 DbContext 类。
在我尝试注册用户之前效果很好...
await IdentityStore.CreateLocalUser(user, model.Password)
返回 false
...没有错误,什么都没有。
有什么解决办法吗?
编辑:
文件名为Models\AppModel.cs
,里面有MyDbContext类
原来是
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
我把它改成了
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
public MyDbContext() : base("MyConnectionString") { }
}
连接字符串正常工作,因为我有其他项目使用相同的字符串,并且它们运行良好。
<connectionStrings>
<add name="MySailorContext" connectionString="Data Source=THOMAS-LAPTOP;Initial Catalog=MySailor;Integrated Security=True;Pooling=False;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
最佳答案
以下是有关如何成功更改数据库的分步说明。首先,清理您之前可能做过的任何事情。如果有任何机会您可能无法获得所有内容,最好是从新文件夹中的全新副本开始。
一旦源 100% 恢复到原始状态,请确保清除所有其他内容,包括删除"new"数据库和原始数据库 (aspnet-AspnetIdentitySample-20130627083537_2)。您可以使用 SQL Server 对象资源管理器找到原始数据库。 (Visual Studio 中的“ View ”->“SQL Server 对象资源管理器”)
接下来,在您第一次运行新应用程序之前,继续进行更改以使用您选择的数据库名称。以下是步骤:
<强>1。在 web.config 中设置新的数据库连接
<connectionStrings>
<!-- Original Connection String -->
<!--
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;
Initial Catalog=aspnet-AspnetIdentitySample-20130627083537_2;Integrated Security=True"
providerName="System.Data.SqlClient" />
-->
<!-- New Connection String -->
<add name="MyConnectionString" connectionString="Data Source=(LocalDb)\v11.0;
Initial Catalog=MyAspnetIdentitySample_1;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
2.修改 AppModel.cs 让 DBContext 使用新连接:
旧:
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
新:
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
public MyDbContext() : base("MyConnectionString") { }
}
3.启用数据库迁移、创建种子数据并更新以验证
3.1- 在包管理器控制台中,启用数据库迁移:
PM> enable-migrations
3.2 - 更新 Migrations\Configuration.cs 以启用自动迁移和种子数据
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(AspnetIdentitySample.Models.MyDbContext context)
{
context.Users.AddOrUpdate(
p => p.UserName,
new MyUser { UserName = "John Doe" }
);
}
3.3 - 通过迁移创建数据库。在包管理器控制台中:
PM> update-database
3.4 - 通过使用 SQL Server 对象资源管理器并查找数据库“MyAspnetIdentitySample_1”来验证您的新数据库是否已创建(并且最初提供的数据库名称不存在)。
4.运行该应用并创建一个新的登录名以验证
这就是您如何从头开始成功完成此操作的方法——如果您不提供更多详细信息,我将无法与您一起/为您解决问题。您应该能够确定哪里出错了。
关于c# - ASP.Net Identity 如何设置目标数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18297052/