Entity Framework CTP4: where to put SetInitializer?

倖福魔咒の 提交于 2019-12-03 14:46:25

Update

I simply glossed over the fact you already have a database and don't want to create another one...in that case the answer is to put this in your SchedulerContext class

protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) {
    modelBuilder.IncludeMetadataInDatabase = false;
}

Old answer

You usually put it in the Global.asax

protected void Application_Start() {
    Database.SetInitializer<SchedulerContext>(new CreateDatabaseOnlyIfNotExists<SchedulerContext>());
}

Note that it will only be initialized on first use of the data context.

Update

public class DataContextInitializer : CreateDatabaseOnlyIfNotExists<SchedulerContext> {
    protected override void Seed(SchedulerContext context) {
    }
}

Then you modify the SetInitializer like so.

System.Data.Entity.Infrastructure.Database.SetInitializer<SchedulerContext>(new  DataContextInitializer());

Btw, as of CTP5, this is the proper way of setting the initializer in Global.asax

protected void Application_Start() { System.Data.Entity.Database.DbDatabase.SetInitializer<NerdDinners>(new System.Data.Entity.Database.DropCreateDatabaseIfModelChanges<NerdDinners>()); }

In EF 4.1

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}

The problem is that ADO.NET team creates the connection as

 connectionBuilder = new SqlConnectionStringBuilder(sqlConnection.ConnectionString)
                {
                    InitialCatalog = "master",
                    AttachDBFilename = string.Empty, 
                };

BUT sqlConnection.ConnectionString is the pure connection string specified in the application config file but without password! due to the security reasons, I think ... so then opening such connection fails!


The only possible solution I found is to use integrated security, which means to set the connection string property Integrated Security=SSPI

And we need to wait while there will be a patch or CTP5 ;o)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!