DbContext class in Asp.net MVC 5 with Identity 2.0

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

Question

When utilizing Entity Framework, you must have a context class that derives from DbContext.

EF is used by Asp.net Identity, and the default template generates the following class:

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

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

This class does not descend from DbContext in any way. Should I make my own db context class for my own data (my classes that I wish to persist to the database)?

I must use both contexts if I want to do an operation that will update both the identity user and one of my own classes. This doesn't feel very natural, therefore.

Should I continue to use my own classes as context for the ApplicationDbContext class as well? Is that possible?

What is the most effective way for me to use identity and EF for my own classes?

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

Accepted Answer

Use a single IdentityDbContext-derived Context class. For further information, see this response.

All of your classes' DbSets must be added to 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