Use EF Code First to build a simple ASP. net mvc website, which allows database migration and efmvc

Source: Internet
Author: User

Use EF Code First to build a simple ASP. net mvc website, which allows database migration and efmvc

This article uses EF Code First to build a simple ASP. net mvc 4 website and allow database migration.

 

Create an ASP. net mvc 4 website.

 

Create the Person class in the Models folder.

 

    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

 

Create a PersonController in the Controls folder, select a template and model class using Entity Framework, and create a data context class as follows:

 

After you click "add", in addition to adding the PersonController to the Controls folder, The PersonContext class is added to the Models folder, as shown below:

 

using System.Data.Entity;
namespace MvcApplication1.Models
{
    public class PersonContext : DbContext
    {
// You can add custom code to this file. Changes are not overwritten.
        // 
// If you want to change the model architecture, Entity Framework
// The system will automatically delete and regenerate the database.
// Add the code to the Application_Start method in the Global. asax file.
// Note: This will be destroyed and the database will be re-created each time the model is changed.
        // 
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<MvcApplication1.Models.PersonContext>());
        public PersonContext() : base("name=PersonContext")
        {
        }
        public DbSet<Person> People { get; set; }
    }
}

 

ConnectionStrings in Web. config has the following configuration and the default localdb database is selected.

 

  <connectionStrings>
    ......
    <add name="PersonContext" connectionString="Data Source=(localdb)\v11.0; Initial Catalog=PersonContext-20150210155119; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|PersonContext-20150210155119.mdf"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

 

Create. cshtml, Delete. cshtml, Details. cshtml, Edit. cshtml, and Index. cshtml are added to the Views/folder.

 

Now, we want to start the automatic Migration Feature of EF. Click "tool"-"Library Program Package Manager"-"Package Manager Console" and enter enable-migrations:

 

A Migrations folder is added to the root directory and a Configuration class is generated as follows:

 

namespace MvcApplication1.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;
    internal sealed class Configuration : DbMigrationsConfiguration<MvcApplication1.Models.PersonContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = false;
        }
        protected override void Seed(MvcApplication1.Models.PersonContext 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" }
            //    );
            //
        }
    }
}

 

Above, we can add some seed data.

 

Now you need to migrate the seed data to the database. On the "Package Manager Console", enter add-migration initial:

 

In this case, the 201502100756322_initial class is added to the Migrations folder, and the Migration action is recorded.

 

namespace MvcApplication1.Migrations
{
    using System;
    using System.Data.Entity.Migrations;
    
    public partial class initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.People",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        FirstName = c.String(),
                        LastName = c.String(),
                    })
                .PrimaryKey(t => t.ID);
            
        }
        
        public override void Down()
        {
            DropTable("dbo.People");
        }
    }
}


Finally, do not forget to update the database. In the "Package Manager Console", enter update-database:

 

In this case, browsing/Person/Index can achieve all the addition, deletion, and modification functions.

 

At this time, we want to add an attribute to Person, such as the Age attribute with the int type.

 

    public class Person
    {
        public int ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }

 

How can we tell the database?

In the "Package Manager Console", enter the add-migration Name:

 

In this case, the 201502100812315_addedage class is added to the Migrations folder, and the Migration action is recorded.

 

Finally, in the "Package Manager Console", enter update-database to update the database.

 

To synchronize the view with the current Person class, you can delete the Person folder and the PersonController controller, recreate the PersonController controller, and select the template, Person class, And PersonContext context class using the Entity Framework.

 

At this point, we have briefly experienced how to create a database with EF Code First and migrate the database.

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.