Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET MVC 3 Entity Framework Disable Code First

I am doing the ASP .NET MVC3 Music store tutorial and instead of connecting to the attached database EF is creating a new database in SQLEXPRESS (code first) . How do I prevent this happening.With the configuration I am using the EF should be connecting to existing database - not creating a new one. I have a DbContext Class as below

using System.Data.Entity;
namespace MusicStore.Models
{
    public class MusicStoreEntities:DbContext
    {
        public DbSet<Album> Albums { get; set; }   
        public DbSet<Genre> Genres { get; set; }
    }
}

And my web.config has the following Connection string

<connectionStrings>
    <add name="MusicStoreEntities"
         connectionString="data source=.\SQLEXPRESS;         Integrated Security=SSPI;       
         AttachDBFilename=|DataDirectory|\MvcMusicStore.mdf;       User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
like image 288
josephj1989 Avatar asked Jul 25 '26 22:07

josephj1989


2 Answers

In Application_Start(), set your database initialization strategy to:

DbDatabase.SetInitializer<MusicStoreEntities>(
         new CreateDatabaseIfNotExists<MusicStoreEntities>());

This will use the default initializer and will only create the database if it can't find it. There are actually three possibilities:

  • CreateDatabaseIfNotExists
  • DropCreateDatabaseAlways
  • DropCreateDatabaseIfModelChanges

You can also do some custom initialization by using this in your Application_Start()

Database.SetInitializer<MusicStoreEntities>(new MusicStoreEntityInitializer());

Then, add a new class which derives from one of the three initialization types, depending on what you need.

namespace MusicStore.Models
{
  public class MusicStoreEntityInitializer : 
           CreateDatabaseIfNotExists<MusicStoreEntityInitializer> 
  {
      protected override void Seed(MusicStoreEntity context)
      {
         base.Seed(context);

         // your code to populate db with test data
      }
  } 
}

With this kind of set up, you have a lot of flexibility.

like image 112
Steve Mallory Avatar answered Jul 28 '26 13:07

Steve Mallory


Try setting a null initializer in the constructor of your db context or in Application_Start:

public class MusicStoreEntities: DbContext
{
    public DbSet<Album> Albums { get; set; }   
    public DbSet<Genre> Genres { get; set; }

    public MusicStoreEntities(string connectionString): base(connectionString)
    {
        Database.SetInitializer<MusicStoreEntities>(null);
   }
}

Here's a nice tutorial you might take a look at about EF Code First. And here's a blog post explaining the different initialization options.

like image 36
Darin Dimitrov Avatar answered Jul 28 '26 14:07

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!