EF6: Renaming namespace using Code First Migration

2019-03-13 13:03发布

问题:

It is possible for me to rename the namespace of my entire Project (including of course: DbContext class, Migrations configuration classes, etc) without breaking anything or having to recreate all my migrations?

Say, I have Project MyProject, which namespace is

Foo.MyProject

And my configuration classes are in

Foo.MyProject.Migrations

Say I want to rename Foo namespace for Bar, and of course my Configurations namespace now will be

Bar.MyProject.Configurations

Is there any correct way of doing this and maintain all my current Migrations still working? Do these ways involve manually editing the ___MigrationHistory table or something? (at a glance I see the ContextKey column, which I suspect I should manually edit.)

回答1:

Yes, you do indeed need to update the ContextKey in the__MigrationHistory table. Code:

UPDATE [dbo].[__MigrationHistory] 
   SET [ContextKey] = 'New_Namespace.Migrations.Configuration'
 WHERE [ContextKey] = 'Old_Namespace.Migrations.Configuration'

A good read on the topic of renaming namespaces with EF6:

http://jameschambers.com/2014/02/changing-the-namespace-with-entity-framework-6-0-code-first-databases/