0
votes

I want to create an interface for my ApplicationDbContext. However, it inherits from IdentityDbContext.

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

Currently, IDbContext doesn't have any references to the IdentityDbContext tables such as Users, Roles, etc... So when I use the interface in my code anything that is accessing the Identity tables will not work because the interface doesn't include those. I've tried to add an

IDbSet<ApplicationUser> 

to my ApplicationDbContext so that I can reference it in the interface but it gets confusing because ApplicationUser is a custom implementation of IdentityUser. How can I create this interface so that I can reference all the tables that my ApplicationDbContext has access to, but through the interface?

1
You mean something like DbSet<ApplicationUser> Users { get; set; } in your interface? - DavidG
Yes. Wow, did I just overthink this? - MikeBeers

1 Answers

0
votes

You just need to replicate the properties in your interface. For example:

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

You could also abstract the interface to make it more directly compatible with the Identity objects:

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
}

And tweak your context:

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