Code First (1), Learning codefirst
1. According to your understanding, Code First: generate the corresponding database through the entity class and related configuration to realize ing between the entity and the database, you can also build mappings between generated entities and existing databases through entity classes and related configurations.
Example:
Entity class: StudentInfo, ClassInfo
1 public class ClassInfo 2 {3 public int ID {get; set;} 4 public string Name {get; set ;} 5 // There are many Students in each class 6 public ICollection <StudentInfo> Students {get; set;} 7} 8 public class StudentInfo 9 {10 public int ID {get; set ;} 11 public string Name {get; set;} 12 public char Gender {get; set;} 13 public DateTime Birth {get; set ;} 14 // Each student has a class 15 public ClassInfo {get; set;} 16}View Code
Context: CSContext
1 public class CSContext: DbContext 2 {3 public CSContext (): base ("name = ConnStr ") 4 {5} 6 // set of students and Classes 7 public DbSet <StudentInfo> StudentInfos {get; set;} 8 public DbSet <ClassInfo> ClassInfos {get; set ;} 9} 10View Code
Configuration File: App. Config
1 ...2 <connectionStrings>3 <add name="ConnStr" connectionString="Server=localhost;DataBase=EFDemo;User ID=sa;password=***" providerName="System.Data.SqlClient"/>4 </connectionStrings>5 ...
Console:
1 static void Main (string [] args) 2 {3 // ID is automatically mapped to the primary key of the database 4 ClassInfo classinfo = new Entities. classInfo () {5 Name = "Class 1" 6}; 7 StudentInfo studentinfo = new Entities. studentInfo () {8 Name = "Wang Liang", 9 Gender = 'male', 10 Birth = Convert. toDateTime ("1980-01-01") 11}; 12 var context = new CSContext (); 13 // context. entry <StudentInfo> (studentinfo ). state = System. data. entity. entityState. added; 14 // context. set <StudentInfo> (). add (studentinfo); 15 // context. studentInfos. add (studentinfo); 16 context. entry <ClassInfo> (classinfo ). state = System. data. entity. entityState. added; 17 context. saveChanges (); 18 Console. writeLine ("OK"); 19 Console. readKey (); 20}View Code
Database: automatically create the corresponding database, table, and insert data (automatically generate the corresponding primary and Foreign keys)
1... 2 exec sp_executesql n' INSERT [dbo]. [ClassInfoes] ([Name]) 3 VALUES (@ 0) 4 SELECT [ID] 5 FROM [dbo]. [ClassInfoes] 6 WHERE @ ROWCOUNT> 0 AND [ID] = scope_identity () ', n' @ 0 nvarchar (max )', @ 0 = n' Class 1 '7...