ASP. NET MVC Database context initializer

Source: Internet
Author: User

in ASP. NET MVC and Entity Framework programs, if the database does not exist, the default behavior of EF is to create a new database. If the model class does not match the existing database, an exception is thrown.

By specifying the database context object initializer, you can perform the deletion and re-creation of the database and populate the database with a seed method.

The Entity Framework can automatically create (or delete re-create) databases every time that an ASP. NET MVC application runs. You can specify that every time the program runs, or the model does not match the existing database, to perform a delete re-create operation, by specifying the seed method, EF can automatically call the seed method to populate the data automatically after you re-create the database.

Note: After the seed method is executed in the data migration, the data records in the seed method are restored to the record values in the seed method, that is, the changes that I made in u cannot be saved. The seed method is called after each migration after executing the update-database command to update the data.

In the way of the initializer, if the model class does not change, the seed method in the initializer is not executed, so changes to or deletions of records in the UI are saved.

First scenario: In the development phase, the model class needs to iterate quickly, in order to keep the generated database consistent with the model class, you need to delete the re-creation of the database, but will result in the loss of the test data, so use the EF database initializer and seed method to automatically populate the test data to facilitate testing.

First step: Create the database initializer.

1. Create the dropcreatedatabasealways<dbcontext> database initializer. Delete and recreate database operations every time the program is run

public class Schoolinitializer:dropcreatedatabasealways<schoolcontext>
{

Protected Override void Seed(SchoolcontextContext) { VarStudents= New List<Student> { New Student{Firstmidname="Carson",LastName="Alexander",EnrollmentDate=Datetime.Parse("2005-09-01")}, New Student{Firstmidname="Meredith",LastName="Alonso",EnrollmentDate=Datetime.Parse("2002-09-01")}, New Student{Firstmidname="Arturo",LastName="Anand",EnrollmentDate=Datetime.Parse("2003-09-01")}, New Student{Firstmidname="Gytis",LastName="Barzdukas",EnrollmentDate=Datetime.Parse("2002-09-01")}, New Student{Firstmidname="Yan",LastName="Li",EnrollmentDate=Datetime.Parse("2002-09-01")}, New Student{Firstmidname="Peggy",LastName="Justice",EnrollmentDate=Datetime.Parse("2001-09-01")}, New Student{Firstmidname="Laura",LastName="Norman",EnrollmentDate=Datetime.Parse("2003-09-01")}, New Student{Firstmidname= "Nino" ,lastname= " Olivetto ",enrollmentdate=datetimeparse ( "2005-09-01" }; Students. Foreach (s => context students. Adds Context.< Span class= "Typ" >savechanges ()

2. Create the dropcreatedatabaseifmodelchanges<dbcontext> database initializer. Perform a delete, recreate database operation when the model has changed

public class Schoolinitializer:Dropcreatedatabaseifmodelchanges<schoolcontext>
{
protected override void Seed (Schoolcontext context)
{
var students = new List<student>
{
New Student {firstmidname = "Zhang", lastname= "three", Enrollmentdate=datetime.parse ("1979-9-1")}
New Student {firstmidname = "Li", lastname= "four", Enrollmentdate=datetime.parse ("2000-9-1")},
New Student {firstmidname = "King", Lastname= "two", Enrollmentdate=datetime.parse ("1979-9-1")}
New Student {firstmidname = "Chen", lastname= "Five", Enrollmentdate=datetime.parse ("2000-9-1")},
};

Students. ForEach (s = = context. Students.add (s));
Context. SaveChanges ();

2nd step: Specify the database initializer in the application. There are two ways

1. Configuration in the <EntityFramework> node in the Web. config XML file of the ASP. NET MVC application root

<entityFramework>  <contexts>    <context type="ContosoUniversity.DAL.SchoolContext, contosouniversity">  <databaseinitializer    Type  =  Span class= "ATV" > " ContosoUniversity.DAL.SchoolInitializer, contosouniversity "  />// disabledatabaseinitialization= "true" . You can close the initializer    </context> </CONTEXTS>      

2. Specified by code in the Application_Start method in the global application configuration file global.asax.

Database.setinitializer<schoolcontext> (New Schoolinitializer ());

Second scenario: deployment phase If you need to store initialization data in a deployed product, such as a super Administrator user name, password information in a role permission system, to be able to log in, or perform some other initialization, you also need to define and use a database context initializer, using only Dropcreatedatabaseifmodelchanges<schoolcontext>

First step: Define a database initializer

public class Majorcontextinitializer:dropcreatedatabaseifmodelchanges<majorcontext>
{
protected override void Seed (Majorcontext context)
{
var themelist = new List<bootstraptheme> ()
{
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "Stock", themedescription= "default theme. Black background navigation bar, blue background title ", Isactived=true},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "Cerulean", themedescription= "dark blue background navigation bar, light blue background title", Isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "Cosmo", themedescription= "blue Background nav bar, sky blue background title", Isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), Themename= "Darkly", themedescription= "emerald green background navigation bar, blue-black background title, black Background", isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "flatly", themedescription= "emerald green background navigation bar, blue-black background title", Isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "sandstone", themedescription= "Green background navigation bar, blue black background title", Isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "Spacelab", themedescription= "dark blue background navigation bar, dark blue background title", Isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "Superhero", themedescription= "Orange background navigation bar, orange background title, small word", isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "All", themedescription= "Red background navigation bar, orange background title", Isactived=false},
New Bootstraptheme {Bootstrapthemeid=guid.newguid (). ToString (), themename= "Yeti", themedescription= "Blue background navigation bar, blue background title, small word", isactived=false}
};

If you do not use the Foreach statement traversal, you can also use Themelist.foreach (S =>context. Bootstrapthemes.addorupdate (P =>p.themename,s)) performs upsert operations, themename topic names as different topics.
foreach (var theme in themelist)
{
var _theme = context. Bootstrapthemes.where (x = X.themename = = Theme. ThemeName). FirstOrDefault ();
if (_theme = = null)
{
Context. Bootstrapthemes.add (theme);

}

}
Context. SaveChanges (); The context is actually used here as well. Savechages (). is mainly convenient debugging, positioning errors out where.

Since you can initialize a topic with a static constructor, you should also be able to initialize other Dbset entity set members.
var categorylist = new List<category> ()
{
New category{Categoryid=guid.newguid (). ToString (), categoryname= "professional dynamics", categorydescription= "progress of professional construction", Navbarisshow=true,indexpageisshow=true, Priororder=1},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "Operation mechanism", categorydescription= "system construction Situation", Navbarisshow=true,indexpageisshow=true, priororder= 2},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "Teaching team", categorydescription= "professional leader, teacher team, team building Situation", navbarisshow=true,indexpageisshow=true, Priororder=3},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "practice conditions", categorydescription= "in-school, outside the training base construction", Navbarisshow=true,indexpageisshow=true, Priororder=4},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "training program", categorydescription= "Talent Training Program", Navbarisshow=true,indexpageisshow=true, priororder= 5},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "School-Enterprise cooperation", categorydescription= "school-Enterprise cooperation Situation", navbarisshow=true,indexpageisshow=true, priororder= 6},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "Social service", categorydescription= "social Service Situation", Navbarisshow=true,indexpageisshow=true, priororder= 7},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "Policies and regulations", categorydescription= "higher vocational education system", Navbarisshow=true,indexpageisshow=true, Priororder=8},
New category{Categoryid=guid.newguid (). ToString (), categoryname= "Curriculum system", categorydescription= "curriculum system composition", Navbarisshow=true,indexpageisshow=true, priororder= 9}
};

foreach (var category in categorylist)
{
var _category = context. Categories.where (x = x.categoryname = = category. CategoryName). FirstOrDefault ();
if (_category = = null)
{
Context. Categories.add (category);
}

}

Context. SaveChanges (); The context is actually used here as well. Savechages (). is mainly convenient debugging, positioning errors out where.

Add a default professional name record;
var majorname = new Majorname {Majornameid = Guid.NewGuid (). ToString (), Majornametext = "NC Technology"};
if (context. Majornames.count () ==0)
{
Context. Majornames.add (Majorname);

}
Context. SaveChanges (); The context is actually used here as well. Savechages (). is mainly convenient debugging, positioning errors out where.

Base. Seed (context);
}
}

Step two: Define a database static constructor in the database context object and set the initializer in the static constructor. Each time a database context object is called, it is checked for the existence of these initial values in the database, which slows down the program's responsiveness. This approach is not a best practice.

public class Majorcontext:dbcontext
{
Public dbset<category> Categories {get; set;}

Public dbset<article> articles {get; set;}

Public dbset<course> Courses {get; set;}

Public dbset<resource> Resources {get; set;}

Public dbset<bootstraptheme> bootstrapthemes {get; set;}

Public dbset<majorname> majornames {get; set;}

Public Majorcontext ()
: Base ("Majorcontext")
{ }


Static constructors. MSDN: Static constructors are used to initialize any static data, or to perform specific operations that need to be performed only once. The static constructor is called automatically before the first instance is created or any static members are referenced
Static Majorcontext ()
{
Sets the database initializer, which is loaded when the application is running.
database.setinitializer<majorcontext> (New Majorcontextinitializer ());
}

protected override void Onmodelcreating (Dbmodelbuilder modelBuilder)//onmodelcreating The purpose of the method override is to specify that the name of the table corresponding to the DBSE entity set should be singular, and if there is no such method, the name of the table in the database is customary as a plural name, such as Studnets, Courses
{
Modelbuilder.conventions.remove<pluralizingtablenameconvention> ();
}

}

ASP. NET MVC Database context initializer

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.