C# ASP.Net Identity 如何设置目标数据库?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18297052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.Net Identity how to set target DB?
提问by Nefarion
I am using the ASP.NET Identity Samplefrom the Asp-Team, and i am trying to change the database for the IdentityDbContext
...
我正在使用来自 Asp-Team的ASP.NET Identity Sample,并且我正在尝试更改数据库以IdentityDbContext
...
I tried it with the constructor
我用构造函数试过了
public MyDbContext() : base("MyConnectionString") { } // base is IdentityDbContext
like with a DbContext class.
就像一个 DbContext 类。
That works well until i try to Register a User...
这很好用,直到我尝试注册用户...
await IdentityStore.CreateLocalUser(user, model.Password)
returns false
... no error, nothing.
返回false
......没有错误,没有。
Any ideas how to fix that?
任何想法如何解决这个问题?
Edit:
编辑:
Filename is Models\AppModel.cs
, there is the MyDbContext class
文件名是Models\AppModel.cs
,有MyDbContext class
originally it was
原来是
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
i changed it to
我把它改成
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
public MyDbContext() : base("MyConnectionString") { }
}
the connection string is working because i have other projects using the same, and they run fine.
连接字符串正在工作,因为我有其他项目使用相同的,并且它们运行良好。
<connectionStrings>
<add name="MySailorContext" connectionString="Data Source=THOMAS-LAPTOP;Initial Catalog=MySailor;Integrated Security=True;Pooling=False;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
采纳答案by RobM
Here's a step-by-step on how to successfully change your database. First, clean-up anything you might have done previously. If there is any chance you might not get EVERYTHING, it would be best if you just started with a completely fresh copy in a new folder.
这是有关如何成功更改数据库的分步说明。首先,清理您以前可能做过的任何事情。如果您有可能无法获得所有内容,最好是从新文件夹中的全新副本开始。
Once source is 100% back to original state, ensure everything else is cleaned up, including deleting your "new" database and the original database (aspnet-AspnetIdentitySample-20130627083537_2). You can find the original database using the SQL Server Object Explorer. ("View" -> "SQL Server Object Explorer" in Visual Studio)
一旦源 100% 恢复到原始状态,请确保清除其他所有内容,包括删除“新”数据库和原始数据库 (aspnet-AspnetIdentitySample-20130627083537_2)。您可以使用 SQL Server 对象资源管理器找到原始数据库。(Visual Studio 中的“视图”->“SQL Server 对象资源管理器”)
Next, before you run your new application for the first time, go ahead and make the change to use your database name of choice. Here are the steps:
接下来,在第一次运行新应用程序之前,继续进行更改以使用您选择的数据库名称。以下是步骤:
1. Set new database connection in web.config1.在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. Modify AppModel.cs to have DBContext use new connection:
2.修改AppModel.cs让DBContext使用新的连接:
OLD:
老的:
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}
NEW:
新的:
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
public MyDbContext() : base("MyConnectionString") { }
}
3. Enable database migrations, create seed data and update to validate
3. 启用数据库迁移,创建种子数据并更新以进行验证
3.1- In the package manager console, enable database migrations:
3.1- 在包管理器控制台中,启用数据库迁移:
PM> enable-migrations
3.2 - Update Migrations\Configuration.cs to enable automatic migrations and seed data
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 - Create the database through migration. In the Package Manager Console:
3.3 - 通过迁移创建数据库。在包管理器控制台中:
PM> update-database
3.4 - Validate that your new database was created (and that the originally provided db name doesn't exist) by using SQL Server Object Explorer and looking for the database "MyAspnetIdentitySample_1".
3.4 - 使用 SQL Server 对象资源管理器并查找数据库“MyAspnetIdentitySample_1”来验证您的新数据库是否已创建(并且最初提供的数据库名称不存在)。
4. Run the app and create a new login to verify
4.运行应用程序并创建一个新的登录来验证
This is how you can successfully do it from scratch -- without you providing more detail, I can't troubleshoot it with/for you. You should be able to determine where you went wrong.
这就是您可以从头开始成功完成的方法——如果您不提供更多详细信息,我将无法与您/为您进行故障排除。您应该能够确定哪里出错了。
回答by Joao de Araujo
I had the same problem and struggled a bit since there's not much material in net about ASP.NET Identity yet. After doing a check on the assemblies I found it's actually simple.
我遇到了同样的问题并且有点挣扎,因为网上关于 ASP.NET Identity 的材料还没有太多。在对程序集进行检查后,我发现它实际上很简单。
Just find the place where your AuthenticationIdentityManager is initialized and use the IdentityStore overload to specify your db context, like this:
只需找到您的 AuthenticationIdentityManager 初始化的地方,并使用 IdentityStore 重载来指定您的数据库上下文,如下所示:
IdentityManager = new AuthenticationIdentityManager(new IdentityStore(new Model()));
My model class inherits DbContext. Hope this helps.
我的模型类继承了 DbContext。希望这可以帮助。
回答by Konamiman
If all you need is to change the connection string used by the identity provider, the following is not very elegant but seems to work. Search where the IdentityManager class is instantiated and add the following:
如果您只需要更改身份提供者使用的连接字符串,以下内容不是很优雅,但似乎有效。搜索 IdentityManager 类的实例化位置并添加以下内容:
//Leave this untouched:
IdentityManager = new AuthenticationIdentityManager(new IdentityStore());
//...and add this:
((IdentityStore)identityManager.Store).DbContext.Configuration
.Database.Connection.ConnectionString = "your connection string here";
回答by Poul K. S?rensen
Since there are alot of changes on this when going to RTM, i have updated the SPA template that uses a WebApi controller for all the identity signin and such. Its a really cool template , if you havent seen it.
由于在使用 RTM 时对此有很多更改,因此我更新了使用 WebApi 控制器进行所有身份登录等的 SPA 模板。它是一个非常酷的模板,如果你还没有看到它。
I put all my code here: https://github.com/s093294/aspnet-identity-rtm/tree/master
我把我所有的代码放在这里:https: //github.com/s093294/aspnet-identity-rtm/tree/master
(Do note, its only for inspiration. I only made it work and nothing more. Properly have a bug or two also).
(请注意,它只是为了灵感。我只是让它工作,仅此而已。适当地也有一两个错误)。
回答by Leo
The answer is not valid anymore for the 1.0 version that comes with VS2013 on the new mvc5 application. To do this now:
对于新的 mvc5 应用程序上 VS2013 附带的 1.0 版本,答案不再有效。现在要这样做:
Declare a class like:
声明一个类,如:
public class AppUserStore : UserStore<IdentityUser>
{
public AppUserStore():base(new MY_IDENTITYDBCONTEXT())
{
}
}
And on Startup.Auth.cs change
并在 Startup.Auth.cs 上更改
UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
to
到
UserManagerFactory = () => new UserManager<IdentityUser>(new AppUserStore());
Without this your IdentityDbContext constructor (and OnModelCreating
, for example) will not run when creating a User with asp.net identity.
如果没有这个,您的 IdentityDbContext 构造函数(和OnModelCreating
,例如)在创建具有 asp.net 身份的用户时将不会运行。
回答by Rob Bowman
Look for the class that inherits from IdentityDbConect eg:
查找从 IdentityDbConect 继承的类,例如:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
Then change the "DefaultConnection" to the name of a connection string identified in your web.config.
然后将“DefaultConnection”更改为您的 web.config 中标识的连接字符串的名称。
回答by Terri
RobM has the comprehensive answer and Rob B has the simple answer.
RobM 给出了全面的答案,而 Rob B 给出了简单的答案。
In your scenario, you are setting your base to "MyConnectionString" which in your config file does not exist.
在您的场景中,您将基数设置为“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>
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
public MyDbContext() : base("MyConnectionString") { }
}
Whatever name you give your connectionString has to match whatever you have in your DbContext : base
无论您给 connectionString 起什么名字,都必须与 DbContext 中的任何名称相匹配:base
<connectionStrings>
<add name="MySailorContext" connectionString="Data Source=THOMAS-LAPTOP;Initial Catalog=MySailor;Integrated Security=True;Pooling=False;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
public class MyDbContext : IdentityDbContext<MyUser, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
public MyDbContext() : base("MySailorContext") { }
}