【问题标题】:DbContext class in Asp.net MVC 5 with Identity 2.0带有 Identity 2.0 的 Asp.net MVC 5 中的 DbContext 类
【发布时间】:2015-02-10 21:25:28
【问题描述】:

当您使用实体框架时,您需要有一个派生自 DbContext 的上下文类。

Asp.net Identity 使用 EF,默认模板创建以下类:

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

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

此类不直接从 DbContext 派生。对于我自己的数据(我想保存到数据库的类),我应该创建自己的数据库上下文类吗?

如果我想做一个更新身份用户和我自己的一个类的操作,我需要同时使用这两个上下文。所以这感觉不是很自然。

我是否应该继续使用 ApplicationDbContext 类作为我自己的类的上下文?这样行吗?

在使用身份的同时将 EF 用于我自己的类的最佳方法是什么?

【问题讨论】:

  • 阅读继承链...... IdentityDbContext 是 DbContext 的派生。
  • 我会在我的应用程序中使用单独的上下文,但我也会使用存储库模式,所以在某种程度上它真的没关系。如果您根据许多大公司的 SOP 将您的会员系统部署到与域 db 不同的服务器,则单独的上下文可能很有价值。
  • 您从哪里得知 IdentityDbContext 不是从 DbContext 派生的?

标签: asp.net-mvc entity-framework-6 asp.net-identity


【解决方案1】:

使用从 IdentityDbContext 继承的单个 Context 类。请参阅this answer 了解更多信息。

您需要将所有类的 DbSet 添加到 ApplicationDbContext 中。

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

    //Public DBSets
    public DbSet<LeaveApplication> LeaveApplications { get; set; }
    public DbSet<LeaveStatus> LeaveStatus { get; set; }
    public DbSet<Department> Departments { get; set; }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

【讨论】:

    最近更新 更多