Updating database schema with Entity Framework Cod

2019-01-14 23:52发布

Entity Framework Code First is a great framework for developing new projects. But what about extending an existing database?

For instance what if I simply want to add an additional property to an existing data entity? Is there any "code first" way to do this or will I have to add a database column by hand using SQL Server Management Studio or a similar tool?

All I have found so far is how to regenerate the entire database from scratch when the schema changes, but I don't want to lose my data.

If I'm not mistaken, there is a tool for Ruby on Rails that can generate an SQL script reflecting the new database changes. Is there any way to do this in EF Code First as well?

4条回答
唯我独甜
2楼-- · 2019-01-15 00:06

Visual Studio have a tool Schema Comparison. After code modifying you can generate database, then use Schema Compare to incremental modify your database project or another database

查看更多
家丑人穷心不美
3楼-- · 2019-01-15 00:12

I am working on a similar problem at the moment.

I use EF Model first approach. I use a database project, which is fed by the sql EF generates.

Basically I have a database project as normal, but the table sql is the sql generated by the EF model.

FYI Database projects are capable of producting change scripts on existing databases without loosing all your data. You can set a db project to warn you if the alteration being performed is harmful to data and not to run in such cases.

I am not finished refining my solution (changing the SsdlToSql10.tt which ef uses to produce sql. Making it more friendly to database projects!).

查看更多
倾城 Initia
4楼-- · 2019-01-15 00:19

I'm currently using EntityFramework.Migrations library which addresses the problem of evolving the DB schema. It works creating migration classes which generate SQL scripts to update your schema.

It is still in beta at this time but I found it useful. Unfortunatly you should still generate data migration scripts.

You can find more information here.

查看更多
Bombasti
5楼-- · 2019-01-15 00:27

Unfortunatelly no. There are currently no ways to build database incrementally in EF code-first. ADO.NET team described some approach they are working on but these tools haven't been published yet. The only way is using database or model first approach. It means you can model your changes in database directly and continue with your coding or you can use EDMX model and Database Generation Power Pack to build your DB incrementally. You can still generate DbContext from EDMX by a new T4 template added in EF 4.1 but you will lose your way to defining entity classes (they will be created by a template).

查看更多
登录 后发表回答