Emre K.
Emre K.

Reputation: 2805

DbContext class in Asp.net MVC 5 with Identity 2.0

You need to have a context class that derives from DbContext when you're using Entity Framework.

Asp.net Identity uses EF and the default template creates the below class:

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

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

This class does not derive directly from DbContext. For my own data (my classes that I want to persist to the db) should I create my own db context class?

If I want to do an operation that will update both the identity user and one of my own classes, I need to use both contexts. So this does not feel very natural.

Should I keep using the ApplicationDbContext class as context for my own classes as well? Would that work?

What is the best method to use EF for my own classes while using identity?

Upvotes: 0

Views: 5250

Answers (1)

Dhaust
Dhaust

Reputation: 5550

Use a single Context class inheriting from IdentityDbContext. See this answer for more info.

You need to add DbSets for all your classes into the ApplicationDbContext.

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

    //Public DBSets
    public DbSet<LeaveApplication> LeaveApplications { get; set; }
    public DbSet<LeaveStatus> LeaveStatus { get; set; }
    public DbSet<Department> Departments { get; set; }

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

Upvotes: 2

Related Questions