ASP. NET MVC4 + EF4.1 Series 3 Code First add-migration

Source: Internet
Author: User

This series has been written on the terminal for a long time since the beginning. It is too busy to take care of this time. But I will give you a good answer at the beginning. We hope we can have more time in the future. From generation 3, I started to talk about Code first add-migration. Everyone knows that the previous model first is more intuitive and clear in the design field. However, there is a big defect. Every time you design a domain, you need to re-generate the database structure, which leads to data loss, this is a pain. I think you will have a deep understanding when using Model first. We are glad that we have enough data migration in Code First to solve these problems for us, even if we change the field, we can still maintain our configuration data (such as menu configuration ).

First, open vs to create an Egojit. Domain layer. The next step is very important.

 

On the console, enter install-package entityframework to install entityframework. The default value is 5.0. If so, the installation is successful! It automatically loads the entityframework library and automatically adds the packages. config configuration package for the project. The Code is as follows:

<?xml version="1.0" encoding="utf-8"?><packages>  <package id="EntityFramework" version="5.0.0" targetFramework="net40" /></packages>

In this way, we add EF to our project. You do not need to add them manually.

Then add a User class for our project. Here we just want to test the EF code first add-migration.User code as follows:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;namespace Egojit.Domain{    public class User    {        [Key]        public Guid Id { get; set; }        public string Name { get; set; }        public string Pwd { get; set; }    }}

Simple code. But it is enough for us to understand.

Then we will add the Context class EgojitFrameworkContext for our project. The Code is as follows:

using System;using System.Collections.Generic;using System.Data.Entity;using System.Linq;using System.Text;namespace Egojit.Domain{    public class EgojitFrameworkContext:DbContext    {        public DbSet<User> Users { get; set; }    }}

This EgojitFrameworkContext class needs to inherit from DbContext, which is like a container to manage various classes in our field.

In step 4, we need to configure the database. Otherwise, we do not know which App. config file the database generates. The configuration is as follows:

 

<?xml version="1.0" encoding="utf-8"?><configuration>  <configSections>    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />  </configSections>  <connectionStrings>    <add name="EgojitFrameworkContext" connectionString="Data Source=.;Database=EgojitFramework;user Id=sa;pwd=2011623;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />     </connectionStrings>  <entityFramework>    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />  </entityFramework></configuration>

 

The connectionStrings configuration section is very important. In this way, we can generate a database,
Step 5 needs to be executed in the Nuget ConsoleEnable-migrationsCommand. You need to execute this command for the first time. You do not need to modify the domain later.

This will generate a Migrations folder in the project and generate a class Configuration in this folder. The Code is as follows:
namespace Egojit.Domain.Migrations{    using System;    using System.Data.Entity;    using System.Data.Entity.Migrations;    using System.Linq;    internal sealed class Configuration : DbMigrationsConfiguration<Egojit.Domain.EgojitFrameworkContext>    {        public Configuration()        {            AutomaticMigrationsEnabled = false;        }        protected override void Seed(Egojit.Domain.EgojitFrameworkContext context)        {            //  This method will be called after migrating to the latest version.            //  You can use the DbSet<T>.AddOrUpdate() helper extension method             //  to avoid creating duplicate seed data. E.g.            //            //    context.People.AddOrUpdate(            //      p => p.FullName,            //      new Person { FullName = "Andrew Peters" },            //      new Person { FullName = "Brice Lambson" },            //      new Person { FullName = "Rowan Miller" }            //    );            //        }    }}

Step 6: Execute the add-migration db command.

This will generate code for domain structure changes: the name of this Code class is generated by combining the time name and the db that we added when executing the add-migration command. The code is:
namespace Egojit.Domain.Migrations{    using System;    using System.Data.Entity.Migrations;        public partial class db : DbMigration    {        public override void Up()        {            CreateTable(                "dbo.Users",                c => new                    {                        Id = c.Guid(nullable: false),                        Name = c.String(),                        Pwd = c.String(),                    })                .PrimaryKey(t => t.Id);                    }                public override void Down()        {            DropTable("dbo.Users");        }    }}

From the code, we can see that our domain has been changed and what has been changed.

In the last step, we need to execute the update-database command in Nuget to submit the changes to the database we configured.

In this way, the EgojitFramework database is generated in the database. You can understand the configuration file of App. config. The Users table is also generated.

Of course there is no data in the table. Now we manually add a record:

In this way, we will test whether the data will be cleared when we modify the domain. We add an Age field for the User class. The Code is as follows:

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Linq;using System.Text;namespace Egojit.Domain{    public class User    {        [Key]        public Guid Id { get; set; }        public string Name { get; set; }        public string Pwd { get; set; }        public int? age { get; set; }    }}

Execute add-migration gg and submit the update-database to the database. The code generated by add-migration gg is as follows:

namespace Egojit.Domain.Migrations{    using System;    using System.Data.Entity.Migrations;        public partial class gg : DbMigration    {        public override void Up()        {            AddColumn("dbo.Users", "age", c => c.Int());        }                public override void Down()        {            DropColumn("dbo.Users", "age");        }    }}

 

We can easily see that we have added the age field. We refresh the database to check and find that the previous data is retained:

Now, we are here. The "add-migraion" command is complete, so you don't have to worry about modifying the domain in the future. We only need two commands to make it okay.

Copyright Disclaimer: from gardenia net http://www.zhizinet.com




 

 

 

 

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.