首页 > 代码库 > EntityFramework 学习 一 Change Tracking in Entity Framework

EntityFramework 学习 一 Change Tracking in Entity Framework

EntityFramework自动跟踪上下文中已经加载的实体,DbChangeTracker类给你关于当前实体的所有跟踪信息

注意,每个实体都要有EntityKey(主键)的属性,EntityFramework将不添加没有主键的概念模型

static void Main(string[] args)
{
    using (var ctx = new SchoolDBEntities())
    {

        Console.WriteLine("Find Student");
        var std1 = ctx.Students.Find(1);

        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("---------------------------------------");
}

 

EntityFramework 学习 一 Change Tracking in Entity Framework