Entity framework 使用EF6和Identity创建DbContext接口
我想为我的ApplicationDbContext创建一个接口。但是,它继承自IdentityDbContextEntity framework 使用EF6和Identity创建DbContext接口,entity-framework,dependency-injection,entity-framework-6,asp.net-identity,dbcontext,Entity Framework,Dependency Injection,Entity Framework 6,Asp.net Identity,Dbcontext,我想为我的ApplicationDbContext创建一个接口。但是,它继承自IdentityDbContext public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IDbContext
public class ApplicationDbContext
: IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IDbContext
public类ApplicationDbContext
:IdentityDbContext,IDbContext
当前,IDbContext没有任何对IdentityDbContext表的引用,例如用户、角色等。。。因此,当我在代码中使用接口时,访问标识表的任何内容都将无法工作,因为接口不包含这些内容。我试图添加一个
IDbSet<ApplicationUser>
IDbSet
到我的ApplicationDbContext,以便我可以在接口中引用它,但它会变得混乱,因为ApplicationUser是IdentityUser的自定义实现。如何创建此接口,以便我可以引用ApplicationDbContext可以访问的所有表,但必须通过该接口?您只需复制接口中的属性即可。例如:
public interface IDbContext
{
IDbSet<ApplicationUser> Users { get; set; }
IDbSet<ApplicationRole> Roles { get; set; }
// etc
}
公共接口IDbContext
{
IDbSet用户{get;set;}
IDbSet角色{get;set;}
//等
}
您还可以抽象接口,使其更直接地与标识对象兼容:
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
}
公共接口IDbContext
在哪里TUser:IdentityUser
TRole的位置:IdentityRole
其中TUserLogin:IdentityUserLogin
TUserRole的位置:IdentityUserRole
何处TUserClaim:IdentityUserClaim
{
IDbSet用户{get;set;}
IDbSet角色{get;set;}
//等
}
并调整您的上下文:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, int,
ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>,
IDbContext<ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
public类ApplicationDbContext:IdentityDbContext,
IDbContext
您的意思是界面中类似于DbSet-Users{get;set;}
的内容?是的。哇,我是不是想得太多了?所以当我添加这个时,它说我没有实现IDbContext.Users:“IdentityContext无法实现IDbContext用户,因为它没有匹配的返回类型DbSet”'ApplicationDbContext'没有实现接口成员'IDbContext.Roles'IdentityDbContext.Roles无法实现“IDbContext.Roles”,因为它没有匹配的返回类型“DbSet”。此外,“ApplicationDbContext”未实现接口成员“IDbContext.Users”IdentityDbContext.Users无法实现“IDbContext.Users”,因为它没有匹配的返回类型“DbSet”。是否使用IDbSet而不是DbSet?否,应该是?