Reference:http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/ Adding-a-new-field-to-the-movie-model-and-table
Ext.: http://www.it165.net/pro/html/201403/10653.html
The content of this article:
1, learning entity Framework Code First migration feature (migrations)
2, update the Model class (Add new field in Model Class), and then apply the update to Datebase.
By default, just as we used the models Movie.cs right-click to add database directly, Code First automatically adds a new table to the database to record the newly added DB time and Movie.cs synchronization, and if not synchronized, the Entity framework will run out of error. This way we can find errors in the development process, rather than having to find them at run time.
One, to be Model The Change settings Code First Migrations function ( Setting up Code first migrations for Model changes ), which allows Movie.cs when changing, apply the change to the Database ( Model class and auto-generated database synchronization)
the Delete Moviedbcontext, Delete . mdf file
1.2ctrl+shift+b After you rebuild the solution, open the Suite Manager console:
After the pm> prompt executes the enable-migrations command to turn on the code first migrations function, we now ENTER: Enable-migrations, you can see the prompt command:
We need to enable the following line command in movie, direct copy prompt command:
Enable-migrations-contexttypename MvcMovie.Models.MovieDBContext Open successfully:
The Migrations folder was created under the solution:
1.3, Change Configuration.cs in the Write Seed method, open Configuration.cs, we see
protected override void Seed (MVCMovie.Models.MovieDBContext context) {//This method will be called after migrations This method is called after migrating to the latest version.
//You can use the dbset<t>. addorupdate extension method, Avoid creating duplicate data // 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 ' &NBSP;}, // new Person { FullName = ' Brice lambson ' }, // new person { FullName = ' Rowan miller ' } // ); // }view Code
Update the Seed method:
protected override void Seed (MvcMovie.Models.MovieDBContext context) {context. Movies.addorupdate (i = i.title, new Movie {Title = ' when Harry Met Sally ', R Eleasedate = DateTime.Parse (' 1989-1-11 '), Genre = ' Romantic comedy ', Price = 7.99M},
New Movie {Title = ' ghostbusters ', releasedate = DateTime.Parse (' 1984-3-13 '), Genre = ' comedy ', Price = 8.99M},
New Movie {Title = ' Ghostbusters 2 ', releasedate = DateTime.Parse (' 1986-2-23 '), Genre = ' comedy ', Price = 9.99M},
New Movie {Title = ' Rio Bravo ', releasedate = DateTime.Parse (' 1959-4-15 '), Genre = ' Western ', price = 3.99M}); }view Code
To add a reference:
Code First Migrations at every time Migration You 'll call this later . Seed method to update Database the data in (Insert orupdate) 1, 4 rebuild the solution. Creating a new class for migrations DbMigration
.cs
inherits from DbMigration
, this step will create a new Database, That's why we wanted to delete it movie.mdf
. Execute command in Package Manager console: add-migration Initial
generate intial Migration. "Intial" is an arbitrary name that is used to name the created migration file. This class is used to create a new database
Code first creates a timestamp-_initial.cs, which implements the creation of a database table, and when you update a table in a class, _ Initial.cs will run the table in update Dabatbase, and then the seed method populates the test data into the database tables. These migrated file class files are named and sorted with a timestamp prefix:
public partial class initial : dbmigration { public override void up () { createtable ( ' dbo. Movies ', c => new { id = c.int (Nullable: false, identity: true), &nbsP; title = c.string (), Releasedate = c.datetime (nullable: false), genre = c.string (), price = c.decimal (nullable: false, PRECISION:&NBSP;18,&NBSP;SCALE:&NBSP;2), }) . PrimaryKey (t => t.id); } public override void down () { Droptable (' dbo. Movies '); } }view Code
Now let's run the command pm>update-datebase to create the database and run the Seed method:
If the Update-database method is running, the table already exists because you ran the project after you deleted the table. If so, remove the movie.mdf again and then execute the update-datebase command. If it is still an error, delete the Migrations folder, and then remove Movie.mdf from the above to follow the steps outlined in this article.
Ctrl+f5 Execute the program and we see the Seed data in the method:
two, in Movie Model Add a new attribute field to the field and synchronize the fields to DB of the Table in
Namespace Mvcmovie.models {//moive class is equivalent to a table in a database named Movie, the object that is instantiated is equivalent to one row in the table, the individual properties of the instance (Id,title ...). Equivalent to the column in table public class Movie {public int ID {get; set;} public string Title {get; set;} Public DateTime releasedate {get; set;} public string Genre {get; set;} Public decimal price {get; set;}
public string Rating {get; set;} }//moviedbcontext class, inherited from the DbContext in the Entity Framework, represents the movie data context//moviedbcontext class, reads, stores, and updates the movie class Instance public class Moviedbcontext:dbcontext {public dbset<movie> Movies {get; set;} }}view Code
Ctrl+shift+b rebuild the solution, and then add the rating attribute to each page in the view:
<div class= ' Editor-label ' > @Html. labelfor (model = model. Rating) </div> <div class= ' Editor-field ' > @Html. editorfor (model = model. Rating) @Html. validationmessagefor (model = model. Rating) </div>view Code
Ctrl+f5 run the program, prompt as follows:
This is because we have just added a new attribute field in the model Movie.cs, and the fields in Movie.cs are inconsistent with the table field in the database that already exists:
We use code first migrations to solve this problem: 1, add rating= ' G ' to each object instance in seed, such as:
Context. Movies.addorupdate (i = i.title, new Movie {Title = ' when Harry Met Sally ', Re Leasedate = DateTime.Parse (' 1989-1-11 '), Genre = ' Romantic comedy ', Rating = ' G ', pric E = 7.99M},view Code
2,
Execute the following command pm>add-migration AddRatingMig
This command tells the migration framework to check whether the current movie model is consistent with the movie field in Dabatase, and if not, adds the necessary code to update the DB and the new model consistently:
3, the solution creates a new timestamp-_addratingmig.cs file with the addition and deletion of new columns to ensure model and DB
The fields in the same
namespace mvcmovie.migrations { using System; using System.Data.Entity.Migrations; public partial class AddRatingMig : Dbmigration { public override Void up () { addcolumn (' dbo. Movies ', ' Rating ', c => c.string ()); } public override void down () { dropcolumn (' dbo. Movies ', ' Rating '); } }}view Code
4, execute command pm>update-database
5, after refreshing "moviedbcontext" we see that the attributes added in Movie.cs are synchronized to the table in DB:
The sample data in Migrations Configuration.cs is also populated in database:
6,ctrl+shift+b,ctrl+f5 run, we see that all the pages have Rating:
In this section, we can add new properties to the model and synchronize them to the DB. We also learned to populate the sample data into a table in db. In the next section, we'll add logic validation (validation logic) and business rules to the new data in the model class.
See you ...
MVC Learning 6 Learning to synchronize model updates to DB using the Code First migrations feature