We want to automatically complete the creation of the database and preset the initial values when the program runs. Their context is named Databasecontet.
There are two ways of doing this:
1, add database.setinitializer<databasecontext> (New Databaseinitializer ()) in Global.asax;
2. Add the Contexts node to the configuration file, specifying the class name and namespace in the node
<entityFramework> <contexts> <context type="Database.databasecontext, DataBase"disabledatabaseinitialization="False"> <databaseinitializer type="Database.databaseinitializer, DataBase"/> </context> </contexts> <defaultconnectionfactory type="Database.databasecontext, DataBase"> <parameters> <parameter value="v11.0"/> </parameters> </defaultConnectionFactory> <providers> <provider invariantname="System.Data.SqlClient"Type="System.Data.Entity.SqlServer.SqlProviderServices, Entityframework.sqlserver"/> </providers> </entityFramework>
Where Databasecontext is:
namespacedatabase{ Public classDatabasecontext:dbcontext { PublicDatabasecontext ():Base("default") { //whether to enable lazy loading://true: Lazy Loading: Gets the entity when its navigation property is not loaded and is automatically loaded once the navigation property is used//false: Direct load (Eager loading): Displays the load navigation properties via methods such as include, gets the entity immediately loads the navigation properties specified by the Include This. configuration.lazyloadingenabled =true; This. configuration.autodetectchangesenabled =true;//automatic monitoring of changes, the default value is True } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Base. Onmodelcreating (ModelBuilder); } PublicDbset<usermodels> UserContext {Get;Set; } PublicDbset<pigmodels> Pigcontext {Get;Set; } }}
Custom data initialization method: Databaseinitializer, which inherits dropcreatedatabasealways only for demonstration purposes, is selected as needed in the actual project.
namespacedatabase{ Public classDatabaseinitializer:dropcreatedatabasealways<databasecontext> { protected Override voidSeed (Databasecontext context) {Usermodels M1=NewUsermodels () {Userguid=Guid.NewGuid (). ToString (), UserName="Zhang Yi", Usernumber="0001", Userbirthday="1990.1.1", Usermail="[email protected]", Userphone="13100001111", Password="aaaaaa" }; Usermodels m2=NewUsermodels () {Userguid=Guid.NewGuid (). ToString (), UserName="Zhang Yi", Usernumber="0002", Userbirthday="1989.12.12", Usermail="[email protected]", Userphone="13100002222", Password="aaaaaa" }; Usermodels M3=NewUsermodels () {Userguid=Guid.NewGuid (). ToString (), UserName="Zhang San", Usernumber="0003", Userbirthday="1989.12.12", Usermail="[email protected]", Userphone="13100003333", Password="aaaaaa" }; Try{//Write Databasecontext. Usercontext.add (M1); Context. Usercontext.add (m2); Context. Usercontext.add (m3); Context. SaveChanges (); } Catch(Dbentityvalidationexception dbex) {}Base. Seed (context); } }}
Specific steps:
First installs the EntityFramework through the NuGet tool, I use 6.0 version.
1, establish the entity class:
namespace databasemodels{public class Usermodels { [Required] [Key] public string Userguid {get ; Set } [Required] [Display (name = "user name")] public string UserName {get; set;} [Display (Name = "User work number")] public string Usernumber {get; set;} [Required] [DataType (Datatype.password)] [Display (Name = "password")] public string Password {get; set;} [Display (Name = "date of birth")] public string Userbirthday {get; set;} [Display (Name = "phone number")] public string Userphone {get; set;} [Display (Name = "Mailbox")] public string Usermail {get; set;}} }
2. Establishing the context inheritance DbContext
namespace database{public class Databasecontext:dbcontext {public databasecontext () : Base (" Default ") {// whether lazy loading is enabled: // true: Lazy loading (lazy Loading): When an entity is fetched, its navigation property is not loaded and is automatically loaded once the navigation property is used false: Direct loading (Eager loading): Displays the load navigation properties via methods such as include, gets the entity immediately loads the navigation properties specified by the Include this . Configuration.lazyloadingenabled = true; This. Configuration.autodetectchangesenabled = true; Automatic monitoring of changes, default value True } protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) { Base. Onmodelcreating (ModelBuilder); } Public dbset<usermodels> UserContext {get; set;}} }
3. Create data initial method
namespacedatabase{ Public classDatabaseinitializer:dropcreatedatabasealways<databasecontext> { protected Override voidSeed (Databasecontext context) {Usermodels M1=NewUsermodels () {Userguid=Guid.NewGuid (). ToString (), UserName="Zhang Yi", Usernumber="0001", Userbirthday="1990.1.1", Usermail="[email protected]", Userphone="13100001111", Password="aaaaaa" }; Usermodels m2=NewUsermodels () {Userguid=Guid.NewGuid (). ToString (), UserName="Zhang Yi", Usernumber="0002", Userbirthday="1989.12.12", Usermail="[email protected]", Userphone="13100002222", Password="aaaaaa" }; Usermodels M3=NewUsermodels () {Userguid=Guid.NewGuid (). ToString (), UserName="Zhang San", Usernumber="0003", Userbirthday="1989.12.12", Usermail="[email protected]", Userphone="13100003333", Password="aaaaaa" }; Try{//Write Databasecontext. Usercontext.add (M1); Context. Usercontext.add (m2); Context. Usercontext.add (m3); Context. SaveChanges (); } Catch(Dbentityvalidationexception dbex) {}Base. Seed (context); } }}
4.
Method One, add database.setinitializer<databasecontext> (New Databaseinitializer ()) in Global.asax;
Or: Method Two: Add a node to the configuration file:
<Contexts> <Contexttype= "Database.databasecontext, DataBase"disabledatabaseinitialization= "false"> <Databaseinitializertype= "Database.databaseinitializer, DataBase" /> </Context> </Contexts>
Entityframewrok Codefirst Database Initialization