clockwiseq
clockwiseq

Reputation: 4229

Enable Migrations in Multi-Tier MVC Application

I am creating a new application using MVC 5 (Razor Views), Entity Framework 6 (Code First), ASP.Net Identity 2.0 and Web API. Trying to create a decent de-coupled architecture, I wanted to enable migrations in my data layer, but I have a misunderstanding of how migrations work. Here's my basic solution architecture:

MyApplication Solution
|-Domain Project
    |-Entity1
    |-Entity2
    |-Entity3
|-Data Layer Project (References Domain Project)
    |-DbContext (Inherits from IdentityDbContext)
|-Migrations Folder
|-Service Layer Project (Web API)
|-Business Layer Project
|-MVC Project
    |-Views

As shown above, the Data Layer Project I have enabled migrations by executing the Enable-Migrations command in the Package Manager Console. The problem is, it only scripts the models related to Identity (AspNetUserRoles, AspNetUserLogins, etc.). How does a migration know to include an entity? I need it to script the models in my Domain project and not quite sure how to tell EF/Migrations to do so.

UPDATE:
Per a request, my simple (out-of-the-box via scaffolded by new project) DbContext class below:

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

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

Upvotes: 0

Views: 1158

Answers (1)

rism
rism

Reputation: 12132

The problem is, it only scripts the models related to Identity (AspNetUserRoles, AspNetUserLogins, etc.). How does a migration know to include an entity?

The migration "knows" what to script as it scripts on a per context basis. Look at the Configuration.cs class in the Migrations folder and you will notice that it is a generic class with the DbContext type passed in as follows:

internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>

So it "knows" because you're explicitly telling it by passing in a MyDbContext generic type parameter.

So if you want to add your own entities classes for migration then you should have a DbSet for each of the entities in your DbContext. i.e.

public class MyDbContext : IdentityDbContext<ApplicationUser> {

    public DbSet<Entity1> Entity1s {get;set;}

    public MyDbContext()
        : base("DefaultConnection", throwIfV1Schema: false){}

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

If you don't want to reuse MyDbContext for your custom entites then you can create another context, and add your entity DbSets to that. But then you will have to explicitly enable and update the migrations as per How do I enable EF migrations for multiple contexts to separate databases?

Upvotes: 1

Related Questions