Database migration in Code-first mode in EF

Source: Internet
Author: User
Tags connectionstrings

Original link: http://www.c-sharpcorner.com/UploadFile/3d39b4/code-first-migrations-with-entity-framework/

Series Catalog:

    • Relationship in Entity Framework using the Code first approach with fluent API "" uses EF Code-first mode and fluent API to explore relationships in EF ""
    • Code first migrations with Entity Framework "using EF for Database Migration"
    • CRUD Operations using Entity Framework 5.0 Code First approach in MVC "use EF 5.0 for additions and deletions in MVC"
    • CRUD Operations using the Repository pattern in MVC "use warehousing mode in MVC, to do additions and deletions to check and change"
    • CRUD Operations using the Generic Repository pattern and unit of work in MVC "use generic warehousing mode and working unit in MVC to make additions and deletions"
    • CRUD Operations using the Generic Repository pattern and Dependency injection in MVC "use generic warehousing mode and Dependency injection in MVC to make additions and deletions"

In the previous article, we learned about several relationships in EF, one-to-one, one-to-many, and many-to-many. But I am sure you will have some questions:

1. Do I have to create a database every time?

2. How do I add fields and remove fields from a table that already exists?

3. How do I avoid losing data when I add a field or remove a field to a table?

4. How do I get a script to create a database when the database changes?

Don't worry, this article, I will tell you one by one:

First of all, why do we use database migration technology, because our entities are always changing very frequently, in the previous article, we used the database initialization policy to do, that is, every time when the database does not exist, create a database "similar to several initialization strategies", however, when your entity changes , EF will make an error when using this strategy. and the database migration technology can help us, we don't have to create a database every time. and the database migration technology can also set the initialized data for us.

Let's look at the project structure first:

We need to build 2 class library projects, and a console program:

Student class:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace EF. core{public    class Student    {public        int ID {get; set;}        public string Name {get; set;}        public int Age {get; set;}        public string Sex {get; set;}}    }

Studentmap class:

Using EF. Core;using system;using system.collections.generic;using system.componentmodel.dataannotations.schema;using System.data.entity.modelconfiguration;using system.linq;using system.text;using System.Threading.Tasks;namespace ef.data{public    class studentmap:entitytypeconfiguration<student>    {public        studentmap ()        { This            . Haskey (s = = s.id);            This. Property (s = = s.id). Hasdatabasegeneratedoption (databasegeneratedoption.identity);            This. Property (s = = s.name). Hascolumntype ("nvarchar"). Hasmaxlength (50). IsRequired ();            This. Property (s = = S.sex). Hascolumntype ("nvarchar"). IsRequired ();            This. Property (s = = s.age). IsRequired ();            This. ToTable ("Students");}}}    

EF Context Classes:

Using system;using system.collections.generic;using system.data.entity;using system.linq;using System.Text;using System.threading.tasks;namespace ef.data{public   class Efdbcontext:dbcontext    {public       efdbcontext ()           : Base ("name=dbconnectionstring")       {               }       protected override void Onmodelcreating (Dbmodelbuilder modelBuilder)       {           MODELBUILDER.CONFIGURATIONS.ADD (New Studentmap ());           Base. Onmodelcreating (ModelBuilder);}}}    

Database connection string: "Write in the configuration file for the Ef.data configuration file and console project:" Note also: These two items need to be introduced into EF Server. Represents native

<connectionStrings>    <add name= "dbconnectionstring" connectionstring= "server=.; Database=studentefdb;uid=sa;pwd=password_1 "providername=" System.Data.SqlClient "/>  </ Connectionstrings>

Connectionstring= "server=.;D Atabase=appsdb; Trusted_connection=true "can also

Console:

Using Ef.data;using Ef. Core;using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks ; namespace EF. app{public class Program {static void Main (string[] args) {Console.WriteLine ("Hello, please lose            In the name: "); String name = Console.ReadLine ().            Trim ();            Console.WriteLine ("Please enter Age:");            int result = 0; If the conversion succeeds, result is the correct result if (!int. TryParse (Console.ReadLine ().                Trim (), out result) {Console.WriteLine ("Please enter the correct format of age");            Return            } Console.WriteLine ("Please Enter your gender:");                       string sex = Console.ReadLine ();                    using (Var db=new efdbcontext ()) {Student model = new Student () {                name = name, sex = sex, age = result}; Db. Set<student> (). ADD (model), or the following DB. Entry (model).                state = System.Data.Entity.EntityState.Added; Db.                           SaveChanges ();            } console.write ("success!");                              Console.readkey (); }    }}

After running, write the data.

Look at the data in the database:

Well, this completes the first phase of the preparatory work: now we need to add a field to the student entity email, the project to make a change:

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace EF. core{public    class Student    {public        int ID {get; set;}        public string Name {get; set;}        public int Age {get; set;}        public string Sex {get; set;}        public string Email {get; set;}}}    

Using EF. Core;using system;using system.collections.generic;using system.componentmodel.dataannotations.schema;using System.data.entity.modelconfiguration;using system.linq;using system.text;using System.Threading.Tasks;namespace ef.data{public    class studentmap:entitytypeconfiguration<student>    {public        studentmap ()        { This            . Haskey (s = = s.id);            This. Property (s = = s.id). Hasdatabasegeneratedoption (databasegeneratedoption.identity);            This. Property (s = = s.name). Hascolumntype ("nvarchar"). Hasmaxlength (50). IsRequired ();            This. Property (s = = S.sex). Hascolumntype ("nvarchar"). IsRequired ();            This. Property (s = = s.age). IsRequired ();            This. Property (s = = S.email). IsRequired ();            This. ToTable ("Students");}}}    
Using Ef.data;using Ef. Core;using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks ; namespace EF. app{public class Program {static void Main (string[] args) {Console.WriteLine ("Hello, please lose            In the name: "); String name = Console.ReadLine ().            Trim ();            Console.WriteLine ("Please enter Age:");            int result = 0; If the conversion succeeds, result is the correct result if (!int. TryParse (Console.ReadLine ().                Trim (), out result) {Console.WriteLine ("Please enter the correct format of age");            Return            } Console.WriteLine ("Please Enter your gender:");            string sex = Console.ReadLine ();            Console.WriteLine ("Please enter your email:");                       string email = console.readline ();                    using (Var db=new efdbcontext ()) {Student model = new Student () {  name = name, sex = sex, age = result,                  Email=email}; Db. Set<student> (). ADD (model), or the following db. Entry (model).                state = System.Data.Entity.EntityState.Added; Db.                           SaveChanges ();            } console.write ("success!");                              Console.readkey (); }    }}

After running: error, it is normal, this must be an error, because our entity changed.

How to do?? Don't worry, let's do it. Enable Database Migration technology:

In the package console, enter:

Enable-migrations

Then press ENTER, in the project will generate migration folder, go to see what is inside it.

Then open the Configuration class: Modify the code: ( You must change the parameters of the dbmigrationsconfiguration to the actual class name of the DbContext in your own program namespace+ )

Then enter in the Package Manager console:

Update-database-verbose

OK, now run the project:

See, there is no error. After running, we look at the data in the database:

You can see that the previous data is also in, that is, the data is not lost. Isn't it amazing???

Summary: These two articles summarize some of the uses of EF and hope you like it.

Outside article: Here is the use of the database migration technology in EF. We can add delete fields anytime, anywhere. Instead of having to delete the database manually, you lose data.

Now, I just want to do without a database migration?

I delete the previously generated migration folder "include the Inside class" and then modify the code "delete the email field you just added":

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace EF. core{public    class Student    {public        int ID {get; set;}        public string Name {get; set;}        public int Age {get; set;}        public string Sex {get; set;}       public string Email {get; set;}}}    

Using EF. Core;using system;using system.collections.generic;using system.componentmodel.dataannotations.schema;using System.data.entity.modelconfiguration;using system.linq;using system.text;using System.Threading.Tasks;namespace ef.data{public    class studentmap:entitytypeconfiguration<student>    {public        studentmap ()        { This            . Haskey (s = = s.id);            This. Property (s = = s.id). Hasdatabasegeneratedoption (databasegeneratedoption.identity);            This. Property (s = = s.name). Hascolumntype ("nvarchar"). Hasmaxlength (50). IsRequired ();            This. Property (s = = S.sex). Hascolumntype ("nvarchar"). IsRequired ();            This. Property (s = = s.age). IsRequired ();           This. Property (s = = S.email). IsRequired ();            This. ToTable ("Students");}}}    
Using Ef.data;using Ef. Core;using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks ; namespace EF. app{public class Program {static void Main (string[] args) {Console.WriteLine ("Hello, please lose            In the name: "); String name = Console.ReadLine ().            Trim ();            Console.WriteLine ("Please enter Age:");            int result = 0; If the conversion succeeds, result is the correct result if (!int. TryParse (Console.ReadLine ().                Trim (), out result) {Console.WriteLine ("Please enter the correct format of age");            Return            } Console.WriteLine ("Please Enter your gender:");            string sex = Console.ReadLine ();            Console.WriteLine ("Please enter your email:");                       string email = console.readline ();                    using (Var db=new efdbcontext ()) {Student model = new Student () { name = name, sex = sex, age = ResulT,//Email=email}; Db. Set<student> (). ADD (model), or the following db. Entry (model).                state = System.Data.Entity.EntityState.Added; Db.                           SaveChanges ();            } console.write ("success!");                              Console.readkey (); }    }}

After running, it will certainly be an error, because no database has been migrated:

We make the following changes:

Using system;using system.collections.generic;using system.data.entity;using system.linq;using System.Text;using System.threading.tasks;namespace ef.data{public   class Efdbcontext:dbcontext    {public       efdbcontext ()           : Base ("name=dbconnectionstring")       {            //Set the database initialization policy to null           database.setinitializer<efdbcontext> (NULL);       }       protected override void Onmodelcreating (Dbmodelbuilder modelBuilder)       {           ModelBuilder.Configurations.Add ( New Studentmap ());           Base. Onmodelcreating (ModelBuilder);}}}    

Then run the project, it is good error, this is not the use of database migration technology to do.

Look at the database:

Both ways are possible, but still recommend the official way, the database migration technology.

Database migration in Code-first mode in EF

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.