使用 EF6 和标识创建 DbContext 接口

Creating a DbContext Interface with EF6 and Identity

我想为我的 ApplicationDbContext 创建一个接口。但是,它继承自 IdentityDbContext。

 public class ApplicationDbContext
        : IdentityDbContext<ApplicationUser, ApplicationRole, int,
        ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IDbContext

目前,IDbContext 没有对 IdentityDbContext 表的任何引用,例如用户、角色等...因此,当我在我的代码中使用该接口时,任何访问身份表的内容都将不起作用,因为该接口不包括那些。我尝试添加

IDbSet<ApplicationUser> 

添加到我的 ApplicationDbContext 中,以便我可以在界面中引用它,但它会让人感到困惑,因为 ApplicationUser 是 IdentityUser 的自定义实现。如何创建此接口,以便我可以引用我的 ApplicationDbContext 有权访问的所有表,但要通过该接口?

您只需复制界面中的属性。例如:

public interface IDbContext
{
    IDbSet<ApplicationUser> Users { get; set; }
    IDbSet<ApplicationRole> Roles { get; set; }
    // etc
}

您还可以抽象化接口,使其更直接地与 Identity 对象兼容:

public interface IDbContext<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>
    where TUser : IdentityUser<TKey, TUserLogin, TUserRole, TUserClaim>
    where TRole : IdentityRole<TKey, TUserRole>
    where TUserLogin : IdentityUserLogin<TKey>
    where TUserRole : IdentityUserRole<TKey>
    where TUserClaim : IdentityUserClaim<TKey>
{ 
    IDbSet<TUser> Users { get; set; }
    IDbSet<TRole> Roles { get; set; }
    // etc
}

并调整您的上下文:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int,
        ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>,
    IDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>