All operational data in the Entity Framework is to update the entity state in the EF container
Public enum entitystate { 4, 8, 1, 0x10 , 2 }
1. New
New studentaddress { " address " + DateTime.Now }; Db. Studentaddress.add (address); Console.WriteLine (db. Entry<StudentAddress> (address). State); // added Db. SaveChanges ();
Calling the Add method is essentially changing the entity state to added and then saving it to the database via SaveChanges ()
New studentaddress { " address " + DateTime.Now }; Db. Entry<StudentAddress> (address). state = System.Data.Entity.EntityState.Added; Db. SaveChanges ();
2. Editing
--The first method:
var address2 = db. Studentaddress.firstordefault (); " ModifyFromEf2 "; // db. SaveChanges ();
---1, compared to the value of the Entity field, does not produce a update-sql statement if the value is not changed
--2, modify a field value, update SQL statement will only set modify a field, do not modify all fields
--3, Query 2 times database
--The second method:
New studentaddress { $, "update address " }; // 1, append to the EF container, the status is detached var entityentry = db. Entry (address); // entityentry.state = System.Data.Entity.EntityState.Modified; Db. SaveChanges ();
--1, append a free entity to the EF container
--2. Change EF entity Status to Modified
--3. Modify all fields, regardless of change
--the third method (combined with the first two methods of modification):
--Query the database 1 times
--Modify the specified field
//1, append to the EF container, the status is detached varEntityentry = db. Entry (address);//DetachedConsole.WriteLine ("Append to EF container:"+entityentry.state); //2. Modify the specified field unchanged--> the specified field is modifiedDb. Studentaddress.attach (address);//equivalent to entry. state = System.Data.EntityState.Unchanged; Console.WriteLine ("attach-unchanged:"+ entityentry.state);//unchangedEntityentry.property ("Address"). IsModified =true; Console.WriteLine ("post-modification status:"+ entityentry.state);//Modifieddb. SaveChanges ();
3. Deletion is also true
New studentaddress { u222pdate, "address " + DateTime.Now }; Db. Studentaddress.attach (address); // Detached db. Studentaddress.remove (address); // or change its status to: entitystate.deleted; Db. SaveChanges ();
4. Source code
--Each change in the data will have a corresponding set to hold the changes of these entities
such as: Objectstatemanager
Dictionary<entitykey, entityentry> _addedentitystore
Dictionary<entitykey, entityentry> _deletedentitystore
Dictionary<entitykey, entityentry> _unchangedentitystore
Dictionary<entitykey, entityentry> _modifiedentitystore
--When an entity change occurs, call Addentityentrytodictionary, insert into the collection
--Call SaveChange () to get these changes and manipulate the data
How the 01-entity framework controls data changes