我尝试使用 Entity Framework 6.0 rc1忽略“自动”迁移。我的问题是我现在不想要这个特性,每次我的应用程序运行时,我都可以看到所有的实体日志试图创建所有的表。
期待感谢。
试试这个:
internal sealed class Configuration : DbMigrationsConfiguration<YourContext> { public Configuration() { AutomaticMigrationsEnabled = false; } }
更新:
你也可以试试这个:
Database.SetInitializer<YourContextType>(new CreateDatabaseIfNotExists());
您可以将其放在 app.config 的 entityFramework 部分中:
<contexts> <context type="YourNamespace.YourDbContext, YourAssemblyName" disableDatabaseInitialization="true"/> </contexts>
这个 msdn 页面介绍了 实体架构组的所有内容。
我错在给数据库打电话。SetInitializer (null) ; 太晚了(在上下文已经初始化之后)。确保禁用迁移的最佳方法是在应用程序启动时对所有上下文执行上述调用。相对于在 app.config 中设置它,我更喜欢这种方法,这样我就可以使用容器来定位上下文,然后构造一个调用。
var migrationsMethod = typeof(System.Data.Entity.Database).GetMethod("SetInitializer"); foreach (var contextType in allContextTypes) { migrationsMethod.MakeGenericMethod(contextType).Invoke(null, new object[] { null }); }
也可以在调用 enable-migrations命令(创建 Configuration类)期间配置禁用自动迁移,使用值为 false的 EnableAutomaticMigration参数:
enable-migrations
Configuration
false
EnableAutomaticMigration
enable-migrations -EnableAutomaticMigration:$false -ContextTypeName FullyQualifiedContextName
将创建一个 Configuration类,该类将 AutomaticMigrationsEnabled属性设置为 false,如上面的答案所示。
AutomaticMigrationsEnabled
enable-migrations命令的 EnableAutomaticMigration参数在实体框架教程页面的 这个文章中有提到(但是他们将它与 true一起使用,true似乎是默认值)。
true
通过 web.config 参见-https://msdn.microsoft.com/en-us/data/jj556606.aspx#Initializers
通过代码(奇怪的是,很多的答案更简单)
public class MyDB : DbContext { public MyDB() { Database.SetInitializer<MyDB>(null); } }
或 在 Global.asax.cs 中
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { // ... Database.SetInitializer<MyDB>(null); /// ... } }
如果你发现这个问题希望得到一个简单的答案来禁用迁移,因为你输入了“启用-迁移”,现在事情没有按照你预期的方式运行,比如没有运行你认为它会运行的种子方法,那么在解决方案资源管理器中查看并删除迁移文件夹。这将阻止代码查看迁移配置以查找初始化代码。要恢复“迁移”文件夹,只需再次运行“启用-迁移”。
尝试这样做,在 MyContext 类中添加这一行,这将在调用 MyContext 构造函数之前被调用。这将停止创建数据库,也不会将表添加到已连接的数据库中。基本上,这一行禁用默认的代码优先数据库初始化策略,该策略基本上有一个默认策略,即 CreateDatabaseIfNotExists。
static MyContext() { System.Data.Entity.Database.SetInitializer<MyContext>(null); }