【问题标题】:Asp Identity Custom contextAsp Identity 自定义上下文
【发布时间】:2014-08-17 06:34:43
【问题描述】:

我正在构建一个单页应用程序,所以我使用了 Visual Studio 默认模板。 当它在开发时,我有 2 个数据库 Entityframework.mdf 和 Identity.mdf,因为这是默认配置所做的,但现在我需要与用户建立关系,我无法轻易联系到他们,因为他们在另一个数据库中。

在 MVC 模板中,您可以轻松地这样做:

public class ApplicationUser: IdentityUser
{
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
    public DbSet<CustomTableItem> CustomTable{ get; set; } 
    //You can add more tables
}

当您使用单页应用程序时,它会以我不理解的方式配置用户管理。

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

然后来自this article

此代码使用 UserStore 类的默认构造函数,该构造函数将创建 IdentityDbContext 对象的新实例,因为未提供对象。如果你想使用自己的 IdentityDbContext 派生类,就像 MVC 5 项目那样,你可以修改上面的初始化代码并传入你自己的上下文。

它说我可以修改它但它没有显示如何:(,我已经尝试过但我无法让它工作。这就是我想要做的

UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>());

我错过了什么?

【问题讨论】:

    标签: asp.net-mvc entity-framework asp.net-web-api single-page-application asp.net-identity


    【解决方案1】:

    如果您对UserStore 类使用默认构造函数(不带参数),则会发生这种情况:

    public UserStore()
    {
      this..ctor((DbContext) new IdentityDbContext());
      this.DisposeContext = true;
    }
    

    Identity 框架使用默认连接字符串为您创建自己的数据库上下文,并且与您自己的模型或 DbContext 无关。

    Scott 在他的文章中说UserStore 有一个这样定义的构造函数:

    public UserStore(DbContext context)
    {
      base..ctor(context);
    }
    

    换句话说,您可以将DbContext 作为参数提供给UserStore 的构造函数:

    UserManagerFactory = () => new UserManager<ApplicationUser>(
        new UserStore<ApplicationUser>(new ApplicationDbContext()))
    

    ApplicationDbContext 的定义如您在问题中描述的那样。

    您需要在 ApplicationDbContext 上创建一个迁移,这将在 Entityframework.mdf 中创建身份表。然后,您必须将数据从 Identity.mdf 移动到您的主数据库中。连接到两个数据库并运行如下内容:

    insert into EntityFramework.dbo.IdenetityUsers
    select * from Identity.dbo.IdentityUsers
    

    但是,我只在单个 SQL Server 实例中完成了从一个数据库到另一个数据库的数据迁移,而不是在 LocalDbs 之间(我假设您使用了这些)。所以这个方法可能不起作用,你必须将数据从Identity.mdf导出到csv文件中,然后再导入到EntityFramework.mdf

    【讨论】:

      猜你喜欢
      • 2020-02-01
      • 2016-11-18
      • 1970-01-01
      • 2017-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      相关资源
      最近更新 更多