Manually editing database in code first entity framework

谁说胖子不能爱 提交于 2019-12-21 04:00:18

问题


I have been trying out EF 4.1 (code first) with MVC 3. I am thinking ahead to when the application will need changes. I tested a couple of scenarios. I like the idea of manually editing the database when the model (my POCOs) would changed.

ASP.NET error when I change the model :

"The model backing the 'CTCMContext' context has changed since the database was created. Either manually delete/update the database..."

Now, it says that I can "manually update the database", but I did and still get the same error. Am I missing something !!?!

EDIT

Does this have to do with the model hash generate by EF ?


回答1:


I have had some struggles with this as well. I found that when you let EF create your database for you that a table named dbo.EdmMetadata is created and this is where/how EF tracks the state of the model. I found that if you delete this table after the database has been initially created you will put things into "manual mode" where you can now manually add/remove columns, tables, etc. from your database and EF will not throw the error that you are seeing.

If however you want to keep having EF update your database as you make changes to your model, you will need to create and call a ContextInitializer class that inherits from either DropCreateDatabaseIfModelChanges or DropCreateDatabaseAlways depending upon the behavior that you want to have happen.




回答2:


change the class with the new fieldnames, delete the table "EdmMetaData" then recompile your app.

You will be responsible on modifying the fieldname on your views.

it works for me.




回答3:


As I can see, there aren't really any methods built-in EF for code-first data evolution.

For what was of my initial question, the answer lies in removing the schema generation/validation. It is only then that manually editing the code and database may work.

UPDATE : EF 5.0 now support migrations




回答4:


I know this has been marked as solved but in my case it didn't do the trick.

Once I deleted dbo.EdmMetadata I was getting a different error:

Model compatibility cannot be checked because the database does not contain model metadata. Ensure that IncludeMetadataConvention has been added to the DbModelBuilder conventions.

The way it worked for me was to remove the Initializer class from Application_Start:

void Application_Start(object sender, EventArgs e)
{
    // MyDB.SetInitializer<MyContext>(new MyInitializer());
}


来源:https://stackoverflow.com/questions/6049135/manually-editing-database-in-code-first-entity-framework

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