When you use DbContext.Configuration.AutoDetectChangesEnabled = false to improve performance, then there will be no automatically state tracking (this is what’s causing the performance penalty). To update a entity in the database, including it’s releated entities (navgiation properties), you should use the Entry function on the DbContext:

using System.Data.Entity;
using System.Linq;
[TestMethod]
public void TestChangeTrackingEF()
{
    using (var entities = new MyEntities())
    {
        // Set Configuration.AutoDetectChangesEnabled = false to improve performance (100x).
        entities.Configuration.AutoDetectChangesEnabled = false;

        // By default use lazyloading.
        entities.Configuration.LazyLoadingEnabled = true; 

        // Get a specific entity from the database
        var query = from i in entities.ImageInfo
                    where i.Id == 41
                    select i;
        ImageInfo info = query.First();

        // Update the entity
        info.ProcessStatusId = 9;
                
        // Set state to Modified
        entities.Entry(info).State = System.Data.EntityState.Modified;

        // Save changes to the database.
        entities.SaveChanges();
    }
}

NOTE

Setting the state to EntityState.Modified will update all columns of the object (because change tracking is disabled).

If you only want to update a specific column, for example you know which columns are dirty, then you can use the IsModified property of a DbPropertyEntry object, this object can be obtained by using the Entity.Property() method:

entities.Entry(info).Property("Description").IsModified = true;

One Comment

  1. Hoi Roel, ik heb goede ervaringen met (fluent) nhibernate icm sqlite, heb jij toevallig ervaring met sql ce icm met EF? Met name op het gebied van performance en no-database hosting scenarios. Thx.

    Gerben Rampaart

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.