Asp Identity Custom上下文

时间:2014-08-09 01:08:57

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

我正在构建单页面应用程序,因此我使用了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>());

我想要什么?

1 个答案:

答案 0 :(得分:3)

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

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

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

斯科特在他的文章中说,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

相关问题