Refined. NET 4.0 (10)-automatically update the database structure (Automatic Migrations) under the Code First of ADO. NET Entity Framework 4.3

Source: Internet
Author: User
Tags connectionstrings

[Index page]
[Download source code]

Refined. NET 4.0 (10)-automatically update the database structure (Automatic Migrations) under the Code First of ADO. NET Entity Framework 4.3)

Author: webabcd

Introduction
New Feature of ADO. NET Entity Framework 4.3: automatically update the database structure (Automatic Migrations) under Code First)

Example
Web. config

<? Xml version = "1.0" encoding = "UTF-8"?> <Configuration> <configSections> <section name = "entityFramework" type = "System. data. entity. internal. configFile. entityFrameworkSection, EntityFramework, Version = 4.3.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089 "/> </configSections> <system. web> <compilation debug = "true" targetFramework = "4.0"/> </system. web> <connectionStrings> <! -- You need to set Persist Security Info to True to save the password information because the Database. setInitializer <MyContext> (new DropCreateDatabaseIfModelChanges <MyContext> ()); when determining whether the Code First and database structures are consistent, you need to connect to the master database --> <add name = "MyConnection" providerName = "System. data. sqlClient "connectionString =" server = .; database = MyDB; uid = sa; pwd = 111111; Persist Security Info = True "/> </connectionStrings> </configuration>

Product. cs

Using System; using System. collections. generic; using System. linq; using System. web; using System. componentModel. dataAnnotations; namespace EF43.UpdateSchema {[Table ("Product")] public class Product {[Key] [DatabaseGenerated (DatabaseGeneratedOption. identity)] public int ProductId {get; set;} [Required] [Column ("ProductName", TypeName = "varchar")] public string Name {get; set ;} /* in order to test the miic Migrations, you can release this annotation, and then Add-Migration will automatically generate the Code related to structure Migration public double Price {get; set ;}*/}}

MyContext. cs

Using System; using System. collections. generic; using System. linq; using System. web; using System. data. entity; namespace EF43.UpdateSchema {// The created Context must inherit from DbContext public class MyContext: DbContext {// specify the database connection as MyConnection public MyContext () in connectionStrings (): base ("MyConnection") {} public DbSet <Product> Products {get; set ;}}}

Demo. aspx. cs

/** Download Entity Framework 4.3 through NuGet ** The following describes how to automatically update the database structure (Automatic Migrations) under Code First: * Note: run the following command on the NuGet Package Manager Console ** after updating the object structure: ** 1. Enable-Migrations * to start the migration function, the Migrations folder is generated under the project root directory, which usually contains two files * 1. configuration. cs-related configuration, such as whether automatic migration (false by default) is required * 2. 201202290715581_InitialCreate.cs-data structure before Migration, the first half is divided into timestamp ** 2, Add-Migration-StartupProjectName EF43 * Add a Migration point in the specified project, this command requires you to enter a Name parameter. The value of this parameter is the migration point Name * assume that the input migration Name is MyFirstTest, a file similar to the following will be generated: 201202290718442_MyTestFirst.cs, it contains two methods: Up () and Down (), upgrade and downgrade of the migration point ** 3. Update-Database-StartupProjectName EF43 (upgrade the Database structure of the specified project to the latest) * Update-Database-TargetMigration: "201202290718442_MyTestFirst", upgrade the current Database structure to this migration point (if there is no parameter-TargetMigration, It is upgraded to the latest) * Update-Database-Script, displays the SQL code * Update-Database-Script-SourceMigration: "aaa"-TargetMigration: "bbb ", displays the SQL code used to upgrade/downgrade the migration point "aaa" to the "bbb" of the migration point. ** Note: if the "System. reflection. targetInvocationException: Exception has been thrown by the target of an invocation "Exception. Check whether the specified project name (-StartupProjectName EF43 in this example) */using System; using System is displayed. collections. generic; using System. linq; using System. web; using System. web. UI; using System. web. UI. webControls; using System. data. entity; namespace EF43.UpdateSchema {public partial class Demo: System. web. UI. page {protected void Page_Load (object sender, EventArgs e) {using (var db = new MyContext () {Random random = new Random (); var product = new Product {Name = "windows" + random. next ()}; db. products. add (product); int recordsAffected = db. saveChanges (); Response. write ("affected database rows:" + recordsAffected. toString ());}}}}

Migrations/Configuration. cs

Namespace EF43.Migrations {using System; using System. data. entity; using System. data. entity. migrations; using System. linq; internal sealed class Configuration: DbMigrationsConfiguration <EF43.UpdateSchema. myContext> {public Configuration () {// the database structure is not automatically migrated by default. There are many other related settings. For details, see DbMigrationsConfiguration <TContext> AutomaticMigrationsEnabled = false ;} protected override void Seed (EF43.UpdateSchema. myContext 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 "}//);//}}}

Migrations/201202290715581_InitialCreate.cs

namespace EF43.Migrations{    using System.Data.Entity.Migrations;        public partial class InitialCreate : DbMigration    {        public override void Up()        {            CreateTable(                "Product",                c => new                    {                        ProductId = c.Int(nullable: false, identity: true),                        ProductName = c.String(nullable: false, unicode: false),                    })                .PrimaryKey(t => t.ProductId);                    }                public override void Down()        {            DropTable("Product");        }    }}

Migrations/201202290718442_MyTestFirst.cs

Namespace EF43.Migrations {using System. data. entity. migrations; public partial class MyTestFirst: DbMigration {public override void Up () {// AddColumn ("Product", "Price", c => c. double (nullable: false); // The automatically generated code is as above. The following is my custom code used to set the default value of the newly added field. // there are many other related settings, for details, see DbMigration AddColumn ("Product", "Price", c => c. double (nullable: false, defaultValue: 10d);} public override void Down () {DropColumn ("Product", "Price ");}}}

 

OK
[Download source code]

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.