This chapter mainly describes the use of EF:
The acquisition of EF has been given in the previous chapter
Now you need to create a appmodelcontext
[Dbconfigurationtype (typeof(mysqldbconfiguration))] Public Partial classAppmodelcontext:identitydbcontext<applicationuser, Customidentityrole, Guid, Customuserlogin, CustomUserRole, Customuserclaim> { StaticAppmodelcontext () {} Public StaticAppmodelcontext Create () {return NewAppmodelcontext (); } PublicAppmodelcontext ():Base("name=db") { } PublicDbset<vote> votes {Get;Set; } Public voidSetdebugoutput () { This. Database.Log = (s) = =Debug.WriteLine (s); } protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) {Base. Onmodelcreating (ModelBuilder); Modelbuilder.entity<ApplicationUser> (). Property (P = p.passwordhash). Hasmaxlength ( $); Modelbuilder.entity<ApplicationUser> (). Property (P = p.securitystamp). Hasmaxlength ( $); Modelbuilder.entity<ApplicationUser> (). Property (P = p.phonenumber). Hasmaxlength ( -); Modelbuilder.entity<CustomIdentityRole> (). Property (P = p.name). Hasmaxlength ( -); Modelbuilder.entity<ApplicationUser> (). Property (P = p.username). Hasmaxlength ( -); }
which
Public dbset<link> Links {get; set;}
This code is used to create a data table, and the structure of the data table is created in the link class.
About the content in the link class:
public class Link { [Key] public int Id {get; set;} [Stringlength ()] [Display (name= "title")] public string Title {get; set;} [Stringlength (+)] [URL] [Display (name= "link")] public string Url {get; set;} Public linktype Type {get; set;} public int SchoolID {get; set;} Public linkstate linkstate {get; set;} Public virtual ApplicationUser User {get; set;} Public Guid UserId {get; set;} Public linktype Type {get; set;} public int TypeId {get; set;} }
It contains the primary key [key] string length [Stringlength (50)] filter rule [URL] and display name [Displays (name= "title")]
Public virtual ApplicationUser User {get; set;} Public Guid UserId {get; set;}
is used to define foreign keys
After the table structure is defined
We add content to the context and then enter enable-migration in the package Manager Console
The migration folder is then automatically generated and then entered Add-migration Name
You can then enter update-database to update the database, each time you change the table structure add-migration Name and then update-database can update the table structure, but if there is data in the table and added a non-nullable field, it will be an error.
Using EF, you can map classes directly into a table structure, or you can load database data directly into objects, code error rates can be significantly reduced, code modification costs can be significantly reduced, and EF is a very good framework
C # Blog Essay IX: The use of the EF framework