EF CodeFirst creates a database, efcodefirst
I recently learned a truth, and I will share it with you here: Education represents your past, your present abilities represent your present, and learning represents your future.
Ten years in Hexi, do not bully teenagers
There is no end to learning, keep improving
In other words, EF supports three modes: Code First Model First DataBase First, Microsoft's latest EF framework, that is, EF7 abandoned Model First and DataBase First, as the underlying programmer, we must follow the 'dang '. Since Microsoft has abandoned Model First and Database First, we should also follow the 'dang' line, he expressed his strong support for the 'dang 'Decision and followed the Code First line.
Here: as an example, EF CodeFirst creates a database.
First, create an MVC project and add the following class libraries to the Model:
using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;using System.Data.Entity;using System.Linq;using System.Web;namespace EF_Test.Models{ public class Student { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } public string Sex { get; set; } } public class Course { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } } public class Score { [Key] public int Id { get; set; } public int StudentScore { get; set; } public Student Student { get; set; } public Course Course { get; set; } } public class StudentContext : DbContext { public DbSet<Student> Students { get; set; } public DbSet<Course> Courses { get; set; } public DbSet<Score> Scores { get; set; } }}
Or the following code
Using System; using System. collections. generic; using System. componentModel. dataAnnotations; using System. data. entity; using System. data. entity. modelConfiguration. conventions; using System. linq; using System. web; namespace EF_Test.Models {public class Student {[Key] public int Id {get; set;} [Required] [StringLength (50)] public string Name {get; set ;} [StringLength (2)] public string Sex {get; set ;} [StringLength (50)] public string StudentNum {get; set ;}} public class Course {[Key] public int Id {get; set ;} [Required] [StringLength (50)] public string Name {get; set ;}} public class Score {[Key] public int Id {get; set ;} public int StudentScore {get; set;} public Student {get; set;} public Course {get; set ;}} public class StudentContext: DbContext {public St UdentContext (): base ("StudentContext") {} public DbSet <Student> Students {get; set;} public DbSet <Course> Courses {get; set ;} public DbSet <Score> Scores {get; set ;}/// <summary> // modelBuilder in the OnModelCreating method. conventions. the Remove statement prohibits table names from being diversified. If you do not do this, the generated table will be named Students, Courses, and Enrollments. Instead, the table names will be Student, Course, and Enrollment. The developer does not agree that most table names should be used. This tutorial uses the singular form, but it is important that you choose which one you prefer to include or omit this line of code. /// </Summary> /// <param name = "modelBuilder"> </param> protected override void OnModelCreating (DbModelBuilder modelBuilder) {modelBuilder. conventions. remove <PluralizingTableNameConvention> ();}}}
Then, add the following code to the Controller:
Using System; using System. collections. generic; using System. web; using System. web. mvc; using EF_Test.Models; namespace EF_Test.Controllers {public class HomeController: controller {// <summary> ///// </summary> /// <returns> </returns> public ActionResult Index () {var StudentModel = new Student {Name = "Chen Wolong", Sex = "male"}; var CourseModel = new Course () {Name = "Data Structure "}; var ScoreModel = new Score () {Student = StudentModel, Course = CourseModel, StudentScore = 98}; // using (var context = new StudentContext () {context. students. add (StudentModel); context. courses. add (CourseModel); context. scores. add (ScoreModel); context. saveChanges () ;}; return View ();}}}
The following is an analysis:
We have created three entity classes: Student, Course, and Score, which respectively represent students, courses, and scores.
A context class, StudentContext, inherits from DBContext and has three attributes: Students, Courses, and Scores. These three attributes represent three data tables mapped to Student, Course, and Score respectively.
In the controller, we try to create data for each object and insert data into the database.
Let's run the program:
Running result: no database is generated
The reason is that the connection string is not specified in our project. The connection string I specified is as follows:
Note: The Name value of the connection string must be consistent with the context class. The connection string must be generated with the local machine. My database is:
After adding the connection string, we can generate the database normally, as shown below:
Now the question is, if we modify the Model object, will the database table structure and data change accordingly?
We changed Student:
public class Student { [Key] public int Id { get; set; } [Required] [StringLength(50)] public string Name { get; set; } [StringLength(2)] public string Sex { get; set; } [StringLength(50)] public string StudentNum { get; set; } }
Run the program:
The general meaning is that the data context class structure has changed and the database has been created. Please use code-first data migration to modify the database
What should I do?
At this time, we will introduce another topic: several methods of EF database Initialization
How many database initialization methods does EF have?
If you are interested, you can check my blog: four strategies for Entity FrameWork to initialize the database.
I am also ashamed to say that I wrote the above blog two years ago, and I am still confused about EF.
One step at a time, we will always step into qingcloud. Let's continue:
There are four policies for database initialization by EF:
1. A new database will be created every time a database is run.
Database. SetInitializer <XXXXXContext> (new DropCreateDatabaseAlways <XXXXXContext> ());
2. Only the first running ~ To create a new database ~Default Method
Database. SetInitializer <XXXXXContext> (new CreateDatabaseIfNotExists <XXXXXContext> ());
3. After modifying the model ~ Running ~ Will create a new database
Database. SetInitializer <XXXXXContext> (new DropCreateDatabaseIfModelChanges <XXXXXContext> ());
4. Use your own database. Please configure your own connection string in web. config. Note that the name of the connection string should be the same as that of the context: XXXXContext.
Database. SetInitializer <Models. musicStoreContext> (null );
According to our requirements above: Our model has changed and we should adopt the third form. Therefore, we add the following code in APP_Start:
Add student IDs to the Controller:
Run the project again and we get the following results:
Note: If the database is in use after running, deleting the database fails. Clear the project solution, close the database, and run the project.
You can view the following information for yourself:
Public class StudentContext: DbContext {public StudentContext (): base ("StudentContext") // specify the connection string {} public DbSet <Student> Students {get; set ;} public DbSet <Course> Courses {get; set;} public DbSet <Score> Scores {get; set ;}}
@ Chen Wolong's blog