3

I have two separate unrelated models that I am trying to use in the same database. Here is the code for each:

public class ImageDBContext : DbContext
{
    public ImageDBContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<ImageModel> Images { get; set; }

}

[Table("Images")]
public class ImageModel
{
    [Key]
    public int ID { get; set; }
    public string Type { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string FileName { get; set; }

    [NotMapped]
    public HttpPostedFileBase Attachment { get; set; }
}

Here is the other model

public class TestimonialDBContext : DbContext
{
    public TestimonialDBContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<Testimonial> Testimonials { get; set; }
}

[Table("Testimonials")]
public class Testimonial
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

When I access the view for one model it works great. It doesn't matter which model but when I go to the view for the other model I get this error:

The model backing the 'ImageDBContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

It seems to me like both models are trying to use the same table? The table gets created by the first model that is initialized but then the second model tries to use the the existing table instead of creating its own.

How can I get both models to use their own tables in the database?

Here is the connection string:

 <add name="DefaultConnection" connectionString="Data Source=localhost\SQLEXPRESS;Initial Catalog=--------;User ID=-------;Password=---------" providerName="System.Data.SqlClient" />

Update: I have added the following code to the models and I still get the same error.

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ImageModel>().ToTable("ImagesTable");
    }

and

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Testimonial>().ToTable("TestimonialsTable");
    }
tereško
  • 58,060
  • 25
  • 98
  • 150
Dennis Kiesel
  • 1,902
  • 3
  • 15
  • 20
  • problem in connection string you can recreate model and add conection string design time in webconfig may solve your issue – Black Cloud Apr 11 '13 at 17:32

2 Answers2

3

The error message is deceiving - this cannot/should not be resolved with "Code First Migrations". You have two different DbContexts. If it's the same database then just use one context to which you added both Images and Testimonials.

The way you're doing it, you are basically saying there are two different databases, which use same connection string, and each database has one table, either Images, or Testimonials. So, when you access say Images page, the database gets created with one table Images. But when you access Testimonials it recognizes that the DB structure does not match the model of one Testimonials table and warns you.

Create one DB context like so:

public class MyDBContext : DbContext
{
    public DbSet<ImageModel> Images { get; set; }
    public DbSet<Testimonial> Testimonials { get; set; }
}

And in your controllers just create a new instance of this class when you need to access DB. If you name your connection string (in web.config) as "MyDbContext" you can skip the empty constructor where you need to call base("DefaultConnection").

Floremin
  • 3,969
  • 15
  • 20
  • Works perfect now. It makes sense now as well. Thanks for the quick reply! – Dennis Kiesel Apr 11 '13 at 19:55
  • Hmm... actually it is recommended to split model in multiple DbContexts especcially when working with large databases) But I'm not sure if it's possible with Model-First approach... – Prokurors Oct 11 '13 at 08:21
0

When model is created, migrated and then updated into the Db - EF/CF creates the __MigrationHistory - where it stores the exact EDMX model of your DbContext, entities.

So far, including EF 5 - there is no support for multiple migration tables.

You can theoretically manage to run two migrations together by adjusting migration scripts - and make a db which contains both sets, so that's no an issue.

But when you make two models / DbContext-s - migration table, Db tables layout and your entities do not match - for the same database...

Starting from EF 6 - you'll get support for multi-tenant migrations. i.e. EF6 will allow Multiple Contexts per Database.

For more info and into details see this post of mine...
Migration not working as I wish... Asp.net EntityFramework

Turning migrations off:

The way to work around the issue you're having is to remove migrations. You can simply delete the __MigrationHistory table (it's under system tables), and don't try to engage migrations.

The less 'invasive' method (of turning off migrations) is to do the following...

Database.SetInitializer<FirstContext>(null);
Database.SetInitializer<SecondContext>(null);  

(from here)

Community
  • 1
  • 1
NSGaga-mostly-inactive
  • 14,052
  • 3
  • 41
  • 51
  • Hmmm... Julie Lerman (according to her EF course in pluralsight.com) is actually recommending to split DbContext in to multiple derived contexts (With one BaseContext and one connection string)... – Prokurors Oct 11 '13 at 08:24
  • btw this is so old...I'm no longer recommending the base context any more because we do have much better features to lean on in newer versions of EF – Julie Lerman Jun 22 '16 at 17:39
  • @JulieLerman btw. I know it's 'so' old :) but it doesn't make it any less relevant (your course or the Q/A attempt) - many people are still stuck with older versions for various reasons (and that's only since 6.0 right, 7 is still not out officially, so just one version back really) – NSGaga-mostly-inactive Jun 22 '16 at 23:54
  • I was referring to my recommendation, not the problem. Also \, startng with EF6 , you can use migrations for multiple dbcontexts pointing to the same database. I wanted to mention this earlier with a pointer to somewhere that I discuss this feature in in depth but in the past, I've been accused of being self-serving by pointing to my existing content, rather than recreating it in the SO thread. – Julie Lerman Jun 26 '16 at 18:35