首页 > 代码库 > 01-Entity FrameWork如何控制数据的变化
01-Entity FrameWork如何控制数据的变化
在Entity Framework所有操作数据就是更新EF容器中的实体状态
public enum EntityState { Added = 4, Deleted = 8, Detached = 1, Modified = 0x10, Unchanged = 2 }
1、新增
StudentAddress address = new StudentAddress { Address = "地址" + DateTime.Now }; db.StudentAddress.Add(address); Console.WriteLine(db.Entry<StudentAddress>(address).State);//added db.SaveChanges();
调用Add方法,实际上就是将实体状态改为added,然后通过saveChanges()保存到数据库
StudentAddress address = new StudentAddress { Address = "地址" + DateTime.Now }; db.Entry<StudentAddress>(address).State = System.Data.Entity.EntityState.Added; db.SaveChanges();
2、编辑
--第一种方法:
var address2 = db.StudentAddress.FirstOrDefault(); address2.Address = "ModifyFromEf2";//Modified db.SaveChanges();
-- 1、与实体字段的值作比较,如果值不变,则不会产生update-sql语句
-- 2、修改了某个字段值,update sql语句只会set 修改某个字段,不会修改全部字段
-- 3、查询2次数据库
--第二种方法:
StudentAddress address = new StudentAddress { Id = 36, Address = "update地址" }; //1、追加到EF容器中,状态为Detached var entityEntry = db.Entry(address);//Detached entityEntry.State = System.Data.Entity.EntityState.Modified; db.SaveChanges();
--1、将一个游离的实体 追加到 EF 容器中
-- 2、将EF实体状态改为Modified
-- 3、修改所有的字段,无论是否变化
--第三种方法(综合前两种修改方法):
--查询1次数据库
--修改指定的字段
//1、追加到EF容器中,状态为Detached var entityEntry = db.Entry(address);//Detached Console.WriteLine("追加到EF容器:" + entityEntry.State); //2、修改指定字段Unchanged-->指定字段为修改 db.StudentAddress.Attach(address);//相当于entry.State = System.Data.EntityState.Unchanged; Console.WriteLine("Attach-Unchanged:" + entityEntry.State); //Unchanged entityEntry.Property("Address").IsModified = true; Console.WriteLine("修改后状态:" + entityEntry.State); //Modified db.SaveChanges();
3、删除亦是如此
StudentAddress address = new StudentAddress { Id = 36, Address = "u222pdate地址" + DateTime.Now }; db.StudentAddress.Attach(address);//Detached db.StudentAddress.Remove(address);//或将其状态修改为:EntityState.Deleted; db.SaveChanges();
4、源码
--每一种数据的变化,都会有相应的集合来保存这些实体的变化
如:ObjectStateManager
Dictionary<EntityKey, EntityEntry> _addedEntityStore
Dictionary<EntityKey, EntityEntry> _deletedEntityStore
Dictionary<EntityKey, EntityEntry> _unchangedEntityStore
Dictionary<EntityKey, EntityEntry> _modifiedEntityStore
--当实体变化发生改变时候,调用AddEntityEntryToDictionary,插入到集合中
--调用saveChange(),就会去获取这些变化,进行操作数据
01-Entity FrameWork如何控制数据的变化