ASP.Net Identity如何设置目标数据库?

23
我正在使用Asp-Team的ASP.NET身份示例,并尝试更改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>

  1. 你究竟想做什么?
  2. 在您更改任何代码(包括连接字符串)之前,您是否能够成功创建应用程序中的新用户?
  3. 您到目前为止对应用程序进行了哪些确切的更改?
  4. 更改连接字符串后,您是否启用了迁移并更新了数据库以生成/更新模式?
- RobM
  1. 是的,它成功地工作了。
  2. 只改变了连接字符串和DbContext构造函数。
  3. 是的,我这样做了,否则我会得到一个SqlException。
- Nefarion
@RobM 这正是我所做的唯一一件事... - Nefarion
我正在尝试帮助你,但你需要提供更多信息!文件名、上下文片段包括周围的行……为您的连接字符串提供web.config部分。 - RobM
@RobM:我正在编辑问题,这可能会让评论变得很多... - Nefarion
显示剩余4条评论
7个回答

41

以下是成功更改数据库的步骤。首先,清理之前可能做过的任何事情。如果有任何可能你不能得到所有东西,最好从一个新文件夹中开始,使用完全新的复制。

一旦源代码回到原始状态,确保其他所有内容都已清理干净,包括删除您的“新”数据库和原始数据库(aspnet-AspnetIdentitySample-20130627083537_2)。可以使用SQL Server Object Explorer找到原始数据库。(在Visual Studio中选择“View” -> “SQL Server Object Explorer”)

接下来,在第一次运行新应用程序之前,请继续进行更改,以使用您选择的数据库名称。以下是步骤:


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:

OLD:

    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 - 更新迁移\Migration\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 Object Explorer 并查找数据库"MyAspnetIdentitySample_1"来验证新的数据库是否已创建(并且原始提供的数据库名称不存在)。

4. 运行应用程序并创建一个新的登录以进行验证。

这就是您可以从头开始成功完成它的方法--如果您没有提供更多细节,我无法为您解决问题。您应该能够确定您哪里出了错。


我正在使用Code-First,EF模型已经成功运行,今天我想添加登录功能,但它无法正常工作... - Nefarion
谢谢你的回复,但是再次强调,这不是数据库错误。上下文已经连接到了数据库,只是无缘无故地返回了false。如果有任何异常,都会被重新抛出给我。 - Nefarion
16
我对微软强制推广的新会员技术并不信任。早期的Asp.net Membership非常易于使用,甚至可以从VS中启动配置网站来创建用户和角色。但现在我花费了一个小时才试图弄清如何将自动生成表的mdf更改为真正的SQL服务器。请注意,此处的“crap”是指新技术的质量,不代表其他含义。 - The Muffin Man
为了便于搜索者,我无法停止查看localdb的项目。在执行update-database -verbose时出现的错误是“目标数据库为:'DefaultConnection'(数据源:(localdb)\ mssqllocaldb”。这似乎是解决方法。 - JsAndDotNet

5
答案对于使用新的mvc5应用程序中随VS2013一起提供的1.0版本已不再有效。现在要做到这一点,您需要声明一个类,例如:
public class AppUserStore : UserStore<IdentityUser>
{
    public AppUserStore():base(new MY_IDENTITYDBCONTEXT())
    {

    }
}

在 Startup.Auth.cs 文件中进行更改。
UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());    

为了实现

UserManagerFactory = () => new UserManager<IdentityUser>(new AppUserStore());

如果没有这个,当使用asp.net身份验证创建用户时,您的IdentityDbContext构造函数(以及例如OnModelCreating)将不会运行。


2

我有同样的问题,因为关于ASP.NET身份验证的资料在网络上并不丰富,所以一直很苦恼。但在检查程序集后,我发现其实很简单。

只需找到初始化您的AuthenticationIdentityManager的位置,并使用IdentityStore重载来指定您的数据库上下文,像这样:

IdentityManager = new AuthenticationIdentityManager(new IdentityStore(new Model()));

我的模型类继承自DbContext。希望这可以帮到您。


2

RobM提供了全面的答案,而Rob B则提供了简单的答案。

在您的情况下,您正在将基础设置为“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") { }
}

无论你给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") { }
}

这就是我在那两个部分进行更改时遇到的错误:建立与 SQL 的连接时发生了与网络相关或特定于实例的错误。 - Tony Dong

1
如果你只需要更改身份验证提供程序使用的连接字符串,以下方法并不十分优雅,但似乎可以工作。搜索实例化IdentityManager类的位置,并添加以下内容:
//Leave this untouched:
IdentityManager = new AuthenticationIdentityManager(new IdentityStore());
//...and add this:
((IdentityStore)identityManager.Store).DbContext.Configuration
    .Database.Connection.ConnectionString = "your connection string here";

关于上面的评论,我想提醒一下。你永远不应该把连接字符串放在代码中,作为良好的实践,你应该将其放入appConfig文件中,并从那里使用它,无论何时需要。System.Configuration.ConfigurationManager.AppSettings[key]; - Matias

1

寻找继承自IdentityDbConect的类,例如:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }

然后将“DefaultConnection”更改为在您的web.config中标识的连接字符串的名称。


不起作用,我们需要改更多的地方吗?仅仅改变web.config和applicationDbContext对我来说还不够。 - Tony Dong

1

由于在转换为RTM时进行了许多更改,因此我已更新了使用WebApi控制器进行所有身份登录等操作的SPA模板。如果您还没有看过它,这是一个非常酷的模板。

我把所有的代码都放在这里: https://github.com/s093294/aspnet-identity-rtm/tree/master

(请注意,这仅供参考。我只是让它能够工作,没有做更多的事情。可能会有一两个错误)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接