Entity Framework入門教程(15)---DbContext追蹤實體狀態改變

這一節介紹DbContext追蹤實體的變化。EF支持DbContext在其生命週期中自動追蹤加載的實體。咱們能夠經過DbChangeTracker類獲取DbContext追蹤的全部實體的變化。html

注意每一個實體必須有主鍵值才能被上下文追蹤。概念模型中的實例若是沒有主鍵值,DbContext不會對其執行追蹤。post

下邊的代碼顯示了DbContext追蹤實體狀態變化過程spa

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("

 

輸出爲:code

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(在上下文的生命週期內)都會持續追蹤實體的狀態的改變。htm

 

EF系列目錄連接:Entity Franmework系列教程彙總對象

相關文章
相關標籤/搜索