0

I am using Entity Framework to build an MVC web app in ASP.NET, and am trying to add dependency injection to the database context for easier testing. I have implemented an interface for the application db context like so:

public interface IApplicationDbContext : IDisposable
    {
        DbSet<RequestModel> Requests { get; set; }
        DbSet<ApplicationUser> Users { get; set; }
        int SaveChanges();
        void MarkAsModified(RequestModel request);
    }

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

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

    public DbSet<RequestModel> Requests { get; set; }

    DbSet<ApplicationUser> IApplicationDbContext.Users
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    public void MarkAsModified(RequestModel request)
    {
        Entry(request).State = EntityState.Modified;
    }
}

This it seems very happy with. I then try and initiate the database context on startup to set up the user roles as such:

private void createRolesandUsers()
        {
        IApplicationDbContext db = new ApplicationDbContext();

        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

Under the "db" in the roleManager and userManager lines, I get the following error:

Argument 1: cannot convert Project.Models.IApplicationDbContext to System.Data.Entity.DbContext

I am rather new to Entity Framework and am unsure what I have missed out or mistaken. If anyone has any ideas or can see where I have gone wrong I would greatly appreciate any help or advice.

1 Answers1

0

This just a compilation error happening because your explicitly declared db variable as of your interface type IApplicationDbContext. Just change this line to:

ApplicationDbContext db = new ApplicationDbContext();

or

var db = new ApplicationDbContext();

and it will work.

Koncervator
  • 34
  • 2
  • 2