Below is an example where the category is a user-created entity class, then adds a field and then adds a field to the category table in the database
1.category.cs
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingSystem.Text;namespaceblogappdal.entities{ Public classCategory { Public intId {Get;Set; } [Required] [Stringlength ( $)] Public stringCategoryName {Get;Set; } //Public DateTime CreateDate {get; set;} Public VirtualIcollection<blog> Blogs {Get;Set; } PublicCategory () {Blogs=NewHashset<blog>(); } }}
Start by adding a field with the following code:
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel.DataAnnotations;usingSystem.Linq;usingSystem.Text;namespaceblogappdal.entities{ Public classCategory { Public intId {Get;Set; } [Required] [Stringlength ( $)] Public stringCategoryName {Get;Set; } PublicDateTime CreateDate {Get;Set; } Public VirtualIcollection<blog> Blogs {Get;Set; } PublicCategory () {Blogs=NewHashset<blog>(); } }}
Write the following code in the context:
The code is as follows:
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Data.Entity;usingblogappdal.entities;usingSystem.Data.Entity.ModelConfiguration.Conventions;usingSystem.Data.Entity.Migrations;usingSystem.Data.Entity.Infrastructure;namespaceblogappdal{ Public classBlogappcontext:dbcontext { PublicBlogappcontext ():Base("Name=blogappconn") { //automatically create tables if entity has changed to update to table structureDatabase.setinitializer<blogappcontext> (NewMigratedatabasetolatestversion<blogappcontext, reportingdbmigrationsconfiguration>()); } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {modelBuilder.Conventions.Remove<PluralizingTableNameConvention> ();//The table name is the class name, not the table name with S//contract for removing plural table names } Internal Sealed classReportingdbmigrationsconfiguration:dbmigrationsconfiguration<blogappcontext> { Publicreportingdbmigrationsconfiguration () {automaticmigrationsenabled=true;//any modification of the Model class will update the DB directlyautomaticmigrationdatalossallowed =true; } } Public VirtualDbset<blog> Blogs {Get;Set; } Public VirtualDbset<category> Categories {Get;Set; } Public VirtualDbset<comment> Comments {Get;Set; } Public VirtualDbset<role> Roles {Get;Set; } Public VirtualDbset<user> Users {Get;Set; } }}
Then run the next program to update the tables in the database.
MVC Code First how to update database tables automatically when entity classes change