0

I have two projects each with their own DbContext class that write to the same SQL Server 2012 database.

The DbContext classes are of the form:

public class BlogDbContext : DbContext
{
    public BlogDbContext()
        : base("CodeFirstTestConnString")
    {
    }

    public BlogDbContext(string connectionString)
        : base(connectionString)
    {
    }

    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //modelBuilder.HasDefaultSchema("blogtest");
    }
}

Using Code First Migrations I can create my tables in the (existing) database by executing the following in each project:

Enable-Migrations
Add-Migration Initial
Update-Database

This works fine, however if I add in the line commented out above to set the default schema (both projects use the same schema), Update-Database fails in the second project with the error "There is already an object named '__MigrationHistory' in the database.".

By running "Update-Database -Verbose" I can see that with the default schema changed, "CREATE TABLE [blogtest].[__MigrationHistory]" is executed for the second project; if I don't change the default schema it only tries to create this table the first time.

Is this a bug in Entity Framework, or am I missing something?

1 Answer 1

0

Turns out that this is reported in Codeplex as a bug in EF6.

https://entityframework.codeplex.com/workitem/1685

The workaround shown there is to use a custom HistoryContext to set the default schema:

internal sealed class Configuration : DbMigrationsConfiguration<ConsoleApplication11.MyContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;

        SetHistoryContextFactory("System.Data.SqlClient", (c, s) => new MyHistoryContext(c, s));
    }
}

internal class MyHistoryContext : HistoryContext
{
    public MyHistoryContext(DbConnection existingConnection, string defaultSchema) : base(existingConnection, defaultSchema)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.HasDefaultSchema("foo");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.