Entity Framework basics-article 2, entityframework
The Entity Framework (EF) is a type of data persistence layer Framework. Other frameworks include NHibernate, ibaties, Dapper, PetaPOCO... and so on, all are based on the ORM idea.
First, we will introduce O/R Mapping (ORM)
1. What is ORM? ORM refers to the mutual conversion between object-oriented object models and relational database data structures. It can be understood as converting table entities and tables (applicable on any platform, such as php, java ).
Traditional ADO.net database operations:
// 1. declare the context DemoTestEntities dbContext = new DemoTestEntities (); // 2. declare an object UserInfo userInfo = new UserInfo (); userInfo. age = 18; // 3. tells EF to add aadbContext to the object above. userInfo. add (userInfo); // 4. tell the context to save the changes to the object to the database to go to dbContext. saveChanges ();
2. Query
Static void Main (string [] args) {// query operation DemoTestEntities dbContext = new DemoTestEntities (); List <UserInfo> list = dbContext. userInfo. where (u => u. name = ""). toList (); list. forEach (u => Console. writeLine (u. toString (); Console. readKey ();} public partial class UserInfo {public override string ToString () // rewrite tostring () {return this. age + "," + this. name ;}}
3. Modify
Static void Main (string [] args) {// modify the DemoTestEntities dbContext = new DemoTestEntities (); UserInfo userInfo = new UserInfo (); userInfo. name = ""; userInfo. age = 20; userInfo. userId = 1; // you must specify the id when modifying and deleting the object. // notify the context to modify the object dbContext. entry <UserInfo> (userInfo ). state = System. data. entityState. modified; // modify the data in a column of the database // dbContext. entry <UserInfo> (userInfo ). property <string> (u => u. name ). isModified = true; // second write Method for modifying data in a column of the database // dbContext. entry <UserInfo> (userInfo ). state = System. data. entityState. unchanged; // dbContext. entry <UserInfo> (userInfo ). property ("Name "). isModified = true; dbContext. saveChanges ();}
4. Delete
Static void Main (string [] args) {// delete operation DemoTestEntities dbContext = new DemoTestEntities (); UserInfo userInfo = new UserInfo (); userInfo. name = ""; userInfo. age = 20; userInfo. userId = 1; // you must specify the id when modifying and deleting the object // notify the context to delete the object dbContext. entry <UserInfo> (userInfo ). state = System. data. entityState. deleted; dbContext. saveChanges ();}View Code