asp.net-mvc - Asp Identity 自定义上下文

标签 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

This code uses the default constructor for the UserStore class, which will create a new instance of an IdentityDbContext object since an object isn’t supplied. If you want to use your own IdentityDbContext derived class, like the MVC 5 project does, you can modify the above initialization code and pass in your own context.

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

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

我错过了什么?

最佳答案

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

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

身份框架使用默认连接字符串为您创建自己的数据库上下文,与您自己的模型或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 表。然后,您必须将数据从 Identity.mdf 移动到主数据库中。连接到两个数据库并运行如下内容:

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

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

关于asp.net-mvc - Asp Identity 自定义上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25214284/

相关文章:

c# - LINQ 表达式包含对与不同上下文关联的查询的引用

asp.net - 使用授权代码流的Web API OAuthAuthorizationServer

nhibernate - 如何在 Web API 异步任务中保留 HttpContext

c# - 如何在没有第三方库的情况下在 04 :00 every day in ASP . NET MVC 5.1 安排方法调用?

javascript - 如何制作自定义 HTML Helper?

c# - 如何编写 XPath 表达式以从其值中选择节点名称

entity-framework - 实体类型<class>不是当前上下文模型的一部分

c# - 在 ASP.NET MVC 5 中创建对象时,何时在 C# 中使用 NEW 关键字

entity-framework - ASP.NET Web API 中 DbContext 的推荐生命周期?

asp.net-web-api - AttributeRouting 参数路由与字符串路由冲突