EntityFramework6中關閉自動識別變動功能提高效率的一點小技巧

   默認狀況下,ef6可以在調用如下方法時自動判別實體是否變動:oop

  • DbSet.Find
  • DbSet.Local
  • DbSet.Remove
  • DbSet.Add
  • DbSet.Attach
  • DbContext.SaveChanges
  • DbContext.GetValidationErrors
  • DbContext.Entry
  • DbChangeTracker.Entries

   當上下文追蹤不少實體,而且你在一個循環中調用不少次這些方法的時候,你能夠在循環以前先關閉自動識別功能,能夠極大提高效率。例如:blog

using (var context = new BloggingContext()) 
{ 
    try 
    { 
        context.Configuration.AutoDetectChangesEnabled = false; 
 
        // Make many calls in a loop 
        foreach (var blog in aLotOfBlogs) 
        { 
            context.Blogs.Add(blog); 
        } 
    } 
    finally 
    { 
        context.Configuration.AutoDetectChangesEnabled = true; 
    } 
}注意不要忘記循環結束後從新開啓這個功能。
相關文章
相關標籤/搜索