Use CodeFirst to create a database and codefirst to create a database

Source: Internet
Author: User

Use CodeFirst to create a database and codefirst to create a database

CodeFirst refers to the creation of the corresponding data structure based on the EF entity class. The creation process is completed by the DotNet framework itself, and the programmer can partially interfere.

1. CodeFirst database Policy

CreateDatabaseIfNotExists: Default policy: if the database does not exist, create a database. However, if the database exists and the entity changes, an exception occurs.

DropCreateDatabaseIfModelChanges: this policy indicates that if the model changes, the database will be re-created and the original database will be deleted.

DropCreateDatabaseAlways: this policy indicates that the database is re-created every time the program is run, which is very useful for development and debugging.

2. Create data when using EF to read data

The procedure is as follows:

1) create a project

2) Add EF entity class

3) Add a DbContext derived class

First, you must introduce the EntityFramework Package. You can use the NuGet console command: Install-Package EntityFramework-Version 5.0.0.

Then define the derived class. You can define the database policy in the constructor or app. config/web. config.

Constructor definition:

1 public class BloggingContext: DbContext 2 {3 public BloggingContext () 4: base ("TestEFConnection") 5 {6 // code-first database policy 7 // default policy: if the database does not exist, create a database. However, if the database exists and the entity changes, an exception occurs. 8 Database. setInitializer (new CreateDatabaseIfNotExists <BloggingContext> (); 9} 10 11 public DbSet <Blog> Blogs {get; set;} 12 public DbSet <Post> Posts {get; set ;} 13}View Code

Web. config definition:

Add to etettings Node

<Add key = "DatabaseInitializerForType Ebuy. website. models. ebuyDataContext, Ebuy. website "value =" System. data. entity. createDatabaseIfNotExists '1 [TestEF. testCodeFirst. bloggingContext, TestEF. testCodeFirst], EntityFramework "/>

TestEF. TestCodeFirst. BloggingContext: indicates the complete class name. TestEF. TestCodeFirst: indicates the Assembly where the class is located.

Note: You can select either of the above two options!

Disable database policies:

<Add key = "DatabaseInitializerForType TestEF. TestCodeFirst. BloggingContext, TestEF. TestCodeFirst" value = "Disabled"/>

This configuration will disable the application CodeFirst from creating a database!

4) read data (Create a database)

The running program uses the EF context (DbContext derived class) to read or write data to the object. After data is submitted, EF deletes or creates a database based on the database policy.

Note: It is best to specify the database connection name (specified in the DbContext derived class constructor). Otherwise, the different database components installed may not achieve the expected results.

The official statement is:

If the local SQL Express instance is available (installed with Visual Studio 2010 by default), Code First creates a database for the instance.

If SQL Express is unavailable, Code First tries to use LocalDb (installed with Visual Studio 2012 by default) to create a database.

3. actively migrate data using Migration commands

The CreateDatabaseIfNotExists policy is used by default in CodeFirst mode. Therefore, during development, the error message "data structure has been changed and data needs to be updated" is often displayed. In this case, Code First migration is required.

The migration command consists of the following parts:

Enable-Migrations: Start CodeFirst data migration. The first migration will create a Migrations folder, including: Configuration. cs, <timestamp> _ InitialCreate. cs (this file is not created if the current database does not exist ).

Add-Migration: the command checks whether there have been any changes since the last Migration, and creates a new Migration using all the changes. You can specify a name for the Migration.

Update-Database: This command applies all pending migrations to the Database

1) existing database

After using the steps described above to create a database, CodeFirst will add a migration record in the _ MigrationHistory table of the current database, as shown in:

When you use the Enable-Migrations command to initialize CodeFirst, the file corresponding to the MigrationId will be created in the Migrations project folder.

If the object model changes, you can use the Add-Migration [Migration file name] command to generate the file to be migrated, and then use the Update-Database command to submit the change.

2) No current database

Run Entity-Migrations to create the Migrations folder (including Configuration. cs only)

Run Add-Migration [Migration file name].

Execute Update-Database to create a Database

Query database: select * from _ MigrationHistory, and you will find the migration record. MigrationId is the migration file name corresponding to the project.

 

Reference: https://msdn.microsoft.com/zh-cn/data/jj193542

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.