Automatic database structure update under Code First (Automatic migrations)

Source: Internet
Author: User
Tags connectionstrings

Example Web. config

<?XML version= "1.0" encoding= "Utf-8"?><Configuration><configsections><SectionName= "EntityFramework"Type= "System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, version=4.3.0.0, culture= Neutral, publickeytoken=b77a5c561934e089 "/></configsections><System.Web><CompilationDebug= "true"TargetFramework= "4.0"/></System.Web><ConnectionStrings><!--Persist Security info needs to be set to True to save password information because database.setinitializer<mycontext> (new Dropcreatedatabaseifmodelchanges<mycontext> ()); You need to connect to the master library when judging if Code first is consistent with the database structure--  <add name= "MyConnection "providerName = "System.Data.SqlClient"  ConnectionString= "server=.; database=mydb;uid=sa;pwd=111111; Persist Security info=true " /> </connectionStrings></configuration  >               

Product.cs

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;Usingsystem.web;UsingSystem.ComponentModel.DataAnnotations;NamespaceEF43. updateschema{[Table ("Product")]PublicClassProduct {[Key] [databasegenerated (databasegeneratedoption.identity)]public int ProductId {get; set;} [Required] [Column ( "productname "varchar" )] public string Name {get; set;} /* in order to test Automatic migrations You can release this comment and add-migration The corresponding code for the structure migration will be generated automatically public double price {get; set;} */}}         

MyContext.cs

UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;Usingsystem.web;UsingSystem.Data.Entity;namespace EF43. updateschema{// Create a Context to inherit from DbContext public class Mycontext:dbcontext {// Specify the database connection as: MyConnection public Mycontext (): base (" myconnection ") {} public dbset<product> Products {get; set         

Demo.aspx.cs

/* * Download Entity Framework 4.3 * with nuget * For instructions on automatically updating the database structure under Code first (Automatic migrations): * Note: The package M required through NuGet Anager Console Input Related command * * After updating the entity structure, enter the following command * 1, enable-migrations * Start the migration function, will be generated under the project root directory Migrations folder, there will usually be two files * 1 . Configuration.cs-related configurations, such as whether automatic migration is required (false by default), etc. * 2. 201202290715581_initialcreate.cs-the data structure before migration, the first half is timestamp * * 2, Add-migration-startupprojectname EF43 * Adds a move in the specified project  Move point, this command will require the input of a name parameter, the value of this parameter is the migration point name * Assuming that the input migration names called Myfirsttest will generate a file similar to the following 201202290718442_mytestfirst.cs, which contains two methods up () and down (), respectively, for the upgrade and demotion of this migration point * * 3, Update-database-startupprojectname EF43 (Upgrade the database structure of the specified project to the latest) * Update-database-tar Getmigration: "201202290718442_mytestfirst", upgrade the current database structure to this migration point (no parameter-targetmigration is upgraded to the latest) * Update-database-script, Displays the relevant SQL code for updating the database structure * update-database-script-sourcemigration: "AAA"-targetmigration: "BBB", which displays the migration point "AAA" up/down to the migration point "BBB "The relevant SQL code * Note: If" System.Reflection.TargetInvocationException:Exception has been tHrown by the target of an invocation "exception, see if the project name specified is displayed (this example is-startupprojectname EF43)  */UsingSystem;UsingSystem.Collections.Generic;UsingSystem.Linq;Usingsystem.web;UsingSystem.Web.UI;UsingSystem.Web.UI.WebControls;UsingSystem.Data.Entity;NamespaceEF43. updateschema{PublicPartialClassDemo:System.Web.UI.Page {Protectedvoid 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 ( " The number of rows that affect the database:  "+ recordsaffected.tostring ());}}}    

Migrations/configuration.cs

NamespaceEF43. migrations{UsingSystem;UsingSystem.Data.Entity;UsingSystem.Data.Entity.Migrations;UsingSystem.Linq;InternalSealedClass configuration:dbmigrationsconfiguration<ef43. Updateschema.mycontext>{PublicConfiguration () {//The database structure is not automatically migrated by default, and there are many other related settings, see dbmigrationsconfiguration<tcontext> automaticmigrationsenabled =False; }ProtectedOverridevoidSeed (EF43. Updateschema.mycontext context) {//This method is 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

NamespaceEF43. migrations{UsingSystem.Data.Entity.Migrations;PublicPartialClassinitialcreate:dbmigration {PublicOverridevoidUp () {createtable ( "product" new {ProductId = C.int (nullable: Span style= "COLOR: #0000ff" >false, Identity: truefalse, Unicode: false< Span style= "color: #000000"),}). PrimaryKey (t => T.productid);} public override void down () {droptable ( "product "); } }} 

Migrations/201202290718442_mytestfirst.cs

NamespaceEF43. migrations{UsingSystem.Data.Entity.Migrations;PublicPartialClassmytestfirst:dbmigration {PublicOverridevoidUp () {//AddColumn ("Product", "price", C = c.double (Nullable:false));//Automatically generated code as above, below is my custom, to set the default value of the new field// There are many other related settings that look at Dbmigration addcolumn ("Product", "price", C = + c.double (nullable: false, defaultvalue:10d)); } public override void down () {Dropcolumn ("Product", "price") ; } }} 

Update database structure automatically under Code first (Automatic migrations)

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.