开发者

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开发者_如何学Python 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>


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜