DbContext class in Asp.net MVC 5 with Identity 2.0

asp.net-identity asp.net-mvc entity-framework-6

Question

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?

1
0
3/7/2015 11:44:34 AM

Accepted Answer

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();
    }
}
2
5/23/2017 12:28:24 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow