Entity Framework入门教程(15)---DbContext追踪实体状态改变
这一节介绍DbContext追踪实体的变化。EF支持DbContext在其生命周期中自动追踪加载的实体。我们可以通过DbChangeTracker类获取DbContext追踪的所有实体的变化。
注意每个实体必须有主键值才能被上下文追踪。概念模型中的实例如果没有主键值,DbContext不会对其执行追踪。
下边的代码显示了DbContext追踪实体状态变化过程
static void Main(string[] args) { using (var ctx = new SchoolDBEntities()) { Console.WriteLine("Find Student"); var std1 = ctx.Students.Find(1); //ctx.ChangeTracker.Enties()方法获取所有追踪实体的DbEntityEntry对象 Console.WriteLine("Context tracking changes of {0} entity.", ctx.ChangeTracker.Entries().Count()); DisplayTrackedEntities(ctx.ChangeTracker); Console.WriteLine("Find Standard"); var standard = ctx.Standards.Find(1); Console.WriteLine("Context tracking changes of {0} entities.", ctx.ChangeTracker.Entries().Count()); Console.WriteLine(""); Console.WriteLine("Editing Standard"); standard.StandardName = "Edited name"; DisplayTrackedEntities(ctx.ChangeTracker); Teacher tchr = new Teacher() { TeacherName = "new teacher" }; Console.WriteLine("Adding New Teacher"); ctx.Teachers.Add(tchr); Console.WriteLine(""); Console.WriteLine("Context tracking changes of {0} entities.", ctx.ChangeTracker.Entries().Count()); DisplayTrackedEntities(ctx.ChangeTracker); Console.WriteLine("Remove Student"); Console.WriteLine(""); ctx.Students.Remove(std1); DisplayTrackedEntities(ctx.ChangeTracker); } } private static void DisplayTrackedEntities(DbChangeTracker changeTracker) { Console.WriteLine(""); var entries = changeTracker.Entries(); foreach (var entry in entries) { Console.WriteLine("Entity Name: {0}", entry.Entity.GetType().FullName); Console.WriteLine("Status: {0}", entry.State); } Console.WriteLine(""); Console.WriteLine("
输出为:
Find Student Context tracking changes of 1 entity. Entity Name: EFTutorials.Student Status: Unchanged --------------------------------------- Find Standard Context tracking changes of 2 entities. Editing Standard Entity Name: EFTutorials.Standard Status: Modified Entity Name: EFTutorials.Student Status: Unchanged --------------------------------------- Adding New Teacher Context tracking changes of 3 entities. Entity Name: EFTutorials.Teacher Status: Added Entity Name: EFTutorials.Standard Status: Modified Entity Name: EFTutorials.Student Status: Unchanged --------------------------------------- Remove Student Entity Name: EFTutorials.Teacher Status: Added Entity Name: EFTutorials.Standard Status: Modified Entity Name: EFTutorials.Student Status: Deleted ---------------------------------------
通过上边的栗子可以:无论我们进行是哪种操作(获取,添加,修改,删除),DbContext(在上下文的生命周期内)都会持续追踪实体的状态的改变。
EF系列目录链接:Entity Franmework系列教程汇总