我想为我的ApplicationDbContext创建一个接口。但是,它继承自 IdentityDbContext。
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IDbContext
目前,IDbContext 没有任何对 IdentityDbContext 表的引用,例如用户、角色等。因此,当我在代码中使用接口时,访问 Identity 表的任何内容都将不起作用,因为接口不包含这些表。我试图添加一个
IDbSet<ApplicationUser>
到我的ApplicationDbContext,以便我可以在界面中引用它,但它变得令人困惑,因为ApplicationUser是IdentityUser的自定义实现。如何创建此接口,以便可以通过该接口引用我的应用程序数据库上下文有权访问的所有表?
您只需要在界面中复制属性即可。例如:
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>