实体框架CTP4:往哪里放SetInitializer? [英] Entity Framework CTP4: where to put SetInitializer?

查看:331
本文介绍了实体框架CTP4:往哪里放SetInitializer?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图添加实体框架,code首先,到已经运行与测试数据的MVC应用程序,使用CTP4 preVIEW。

I am attempting to add Entity Framework, code first, to an MVC application that's been running with test data, using the CTP4 preview.

我目前收到此错误:

的模式支持了SchedulerContext背景已经改变,因为在创建数据库。无论是手动删除/更新数据库,或拨打Database.SetInitializer与IDatabaseInitializer实例。例如,RecreateDatabaseIfModelChanges战略将自动删除并重新创建数据库,以及可选的新数据的种子吧。

我不希望在所有生成一个数据库,因为我已经有一个数据库。所以,我想加入以下的SchedulerContext构造:

I do not want to generate a database at all, as I already have a database. So I tried adding the following to the SchedulerContext constructor:

Database.SetInitializer<SchedulerContext>(new CreateDatabaseOnlyIfNotExists<SchedulerContext>());

这是没有效果可言 - 下一次它跑我得到了同样的错误。该错误似乎当执行访问数据库中的LINQ语句来发生 - 第一,我觉得

which had no effect at all -- I got the same error the next time it ran. The error seems to occur when it is executing a LINQ statement that accesses the database -- the first, I think.

我应该在哪里把这个说法,或者是这种说法的回答这个问题呢?

Where should I put this statement, or is this statement the answer to this problem at all?

推荐答案

我只是掩盖了一个事实,你已经有一个数据库和的的要创造一个又一个......在这种情况下,答案是把它放到你的SchedulerContext类

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;
}

旧的答案

您通常把它在Global.asax

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.

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

然后你修改SetInitializer像这样。

Then you modify the SetInitializer like so.

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

这篇关于实体框架CTP4:往哪里放SetInitializer?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆