EF architecture ~ CodeFirst data migration and database deletion prevention, efcodefirst

Source: Internet
Author: User

EF architecture ~ CodeFirst data migration and database deletion prevention, efcodefirst

Back to directory

This article introduces two concepts to Prevent Automatic database deletion. This is because the original database is deleted when the data entity changes in code first mode,And add new data tables, but this is unacceptable for our operating environment database,The second problem is data migration. When a new entity is created, how to respond to the database becomes a problem. Of course, the implementation is also very simple.MigrationsTool.

1. Database deletion prevention

Change the base class of your business DbInitializer to CreateDatabaseIfNotExists to solve this problem. This is what needs to be done during data initialization. Generally, we will choose to automatically update the database when the entity changes, however, this method has a big impact, so we do not advocate it.

Public class ManagerInitializer:CreateDatabaseIfNotExists <ManagerContext>{Protected override void Seed (ManagerContext context)
{// Initialization code }}

2. Data Migration

This problem must also be solved. After adding an object, the database does not have a corresponding table, so we need to useMigrationsCommand to update the database, the specific operation is as follows

1. EnableMigrationsFunction

enable-migrations -force

2. update the database

update-database

3. After the program runs successfully,

Now you can view your own database. The newly added entities are automatically added to the database.

It is worth noting that the original data of the database will not be lost during database migration through this method,Even if you add fields to the original table, old data will not be lost, and new fields will have default values.

For EF7, it only supports the Code First mode, so this mode will become the mainstream in the dotnet framework!

Back to directory

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.