将实体框架移动到MVC中的另一个项目会导致重新迁移 [英] Moving Entity framework to another project from MVC causes re-migration
问题描述
然而,现在当我运行解决方案时,它认为我的模型已经改变,并尝试再运行所有的迁移。这个问题似乎在我使用 SetInitializer
,就像我注释掉这行一样,我可以按照正常的方式运行Web应用程序。
public static class DatabaseConfig
{
public static void Initialize()
{
System.Data.Entity.Database。 SetInitializer(新的MigrateDatabaseToLatestVersion< G5DataContext,Configuration>());
//确保在SimpleMembership初始化之前创建数据库
使用(var db = new G5DataContext())
db.Database.Initialize(true);
}
}
直到我试过移动所有的Entity Framework类。这是不可能的,还是我从根本上做错了?
在启动时,EF6查询退出数据库中的迁移,存储在__MigrationHistory表中。该表的一部分是一个上下文键,其中包括实体的命名空间。
如果将所有内容移动到新的命名空间,EF6不会识别以前运行迁移,并尝试重建数据库。
一个快速的解决方案是运行脚本将__MigrationHistory表中的上下文键重命名为新的命名空间。从 http:/ /jameschambers.com/2014/02/changing-the-namespace-with-entity-framework-6-0-code-first-databases/ :
UPDATE [dbo]。[__ MigrationHistory]
SET [ContextKey] ='New_Namespace.Migrations.Configuration'
WHERE [ContextKey] ='Old_Namespace.Migrations.Configuration'
I currently have an asp.net MVC 4 application which contains Entity framework 6 Code First models, DbContext and Migrations. In an attempt to separate this from my web application so I can re-use these database classes in another project I have moved all related Entity Framework classes to their own project.
However now when I run the solution it thinks my model has changed and attempts to run all my migrations once more. The problem appears to be in my use of SetInitializer
as if I comment out this line I can run the web application as per normal.
public static class DatabaseConfig
{
public static void Initialize()
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<G5DataContext, Configuration>());
// make sure the database is created before SimpleMembership is initialised
using (var db = new G5DataContext())
db.Database.Initialize(true);
}
}
This wasn't a problem until I've tried to move all the Entity Framework classes. Is this not possible, or have I done something fundamentally wrong?
At startup, EF6 queries exiting migrations in your database, as stored in the __MigrationHistory table. Part of this table is a context key, which includes the namespace of the entities.
If you move everything to a new namespace, EF6 doesn't recognize any of the previously run migrations, and tries to rebuild the database.
A quick solution is to run a script to rename the context key in the __MigrationHistory table to your new namespace. From http://jameschambers.com/2014/02/changing-the-namespace-with-entity-framework-6-0-code-first-databases/ :
UPDATE [dbo].[__MigrationHistory]
SET [ContextKey] = 'New_Namespace.Migrations.Configuration'
WHERE [ContextKey] = 'Old_Namespace.Migrations.Configuration'
这篇关于将实体框架移动到MVC中的另一个项目会导致重新迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!