1

I am using ASP.NET MVC 5 with EF 6. I am trying to follow DDD patern and I have IdentityContext and AddressContext.

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

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

}

public class AddressContext: DbContext
{
    public AddressContext(): base("DefaultConntection"){}

    public DbSet<Location> Locations { get; set; }
}

When I am trying to extend(add-migration and update-database) my ApplicationUser which belongs to IdentityContext, I am getting "There is already an object named 'Locations' in the database" error.

public class ApplicationUser : IdentityUser
{
    public virtual Nullable<int> LocationId { get; set; }

    public virtual Location Location { get; set; }
}

How could I share Location Entity between IdentityContext and AddressContext?

Any help would be appreciated.

Hov
  • 109
  • 2
  • 9

1 Answers1

1

A solution would be to have a single context, that contains all of your DbSets, and then just use that to update your database(and nothing else), and then turn off database initialization for each of the other contexts. You can do this by setting it in the constructor of your business contexts:. Example:

public class IdentityContext : IdentityDbContext<ApplicationUser>
{
        public IdentityContext()
            : base("DefaultConntection", throwIfV1Schema: false)
    {
        Database.SetInitializer<IdentityContext>(null);
    }

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

}

public class AddressContext: DbContext
{
    public AddressContext(): base("DefaultConntection")
    {
        Database.SetInitializer<AddressContext>(null);
    }

    public DbSet<Location> Locations { get; set; }
}


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

    public DbSet<Location> Locations { get; set; }
    //Additional DbSets here...
}

In this example, the migration context is inheriting from IdentityDbContext<ApplicationUser>, so that it'll include all of your Identity stuff. A better way to handle the initialization, might be to defining a BaseContext class, that has it turned off, and then just inheriting from that base context, as described here:http://msdn.microsoft.com/en-us/magazine/jj883952.aspx. See this link for a similar question with more info: Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

Community
  • 1
  • 1
Tobias
  • 2,811
  • 2
  • 20
  • 31