Entity Framework Codefirst configuration steps, entitycodefirst
Steps for configuring Entity Framework Codefirst:
(1) Installation command: install-package entityframework
(2) create an object class. Pay attention to the usage of virtual keywords in navigation properties.
(3) create a DbContext class and create a DbSet for each entity set;
Specify the base ("AccountContext") in a connection string constructor ").
Set the singular form of the table
Public class AccountContext: DbContext {public AccountContext (): base ("AccountContext") // web. config File database connection string name {} protected override void OnModelCreating (DbModelBuilder modelBuilder) {// specify the table name in the singular form of modelBuilder. conventions. remove <PluralizingTableNameConvention> ();}}
(4) Configure Entity Framework in Web. config
Configure the connection string
(5) Create the Initializer class, use EF to initialize the database, and insert sample data.
Public class AccountInitializer: DropCreateDatabaseIfModelChanges <AccountContext >{/// <summary> // initialize the database, you need to configure EnityFramework /// </summary> /// <param name = "context"> </param> protected override void Seed (AccountContext context) in the configuration file) {// initialize data var sysUsers = new List <SysUser> {new SysUser {UserName = "Tom", Password = "1", Email = "tom@accp.com"}, new SysUser () {UserName = "Jerry", Password = "2", Email = "Jerry@accp.com" }}; sysUsers. forEach (s => context. sysUsers. add (s); context. saveChanges ();}}
(6) modify web. config to notify EF to use the initializer class we just wrote.
<EntityFramework> <! -- In the context configuration section, the value of type corresponds to the value of type in the databaseInitializer configuration section (complete description of the context class, assembly) --> <contexts> <context type = "ResTest. DAL. accountContext, ResTest "> <databaseInitializer type =" ResTest. DAL. accountInitializer, ResTest "> </databaseInitializer> </context> </contexts> </entityFramework>
This configuration is complete!