/// <summary> /// Demostrate how to update POCO entity relationships without change /// tracking proxy. /// </summary> private static void UpdateRelationshipWithoutChangeTrackingProxy() { Console.WriteLine("Update relationships without change tracking proxy..."); try { using (POCOChangeTrackingEntities context = new POCOChangeTrackingEntities()) { // Turn off proxy creation. context.ContextOptions.ProxyCreationEnabled = false; Department department = context.Departments. Single(d => d.Name == "Chinese"); // Create a regular POCO entity. Course newCourse = new Course() { CourseID = 1234, Title = "Classical Chinese Literature", Credits = 4, StatusID = true }; // Set the relationship. department.Courses.Add(newCourse); Console.WriteLine("Is the newly created object a proxy? {0}", IsProxy(newCourse)); // Retrieve all the newly added entities' object state entry before // DetectChanges is called. var addedBeforeDetectChanges = context.ObjectStateManager. GetObjectStateEntries(EntityState.Added); // It should be no entity added. Console.WriteLine("Before DetectChanges is called, " + "{0} object(s) added", addedBeforeDetectChanges.Count()); // Detect the entity relationships modification. context.DetectChanges(); // Retrieve all the newly added entities' object state entry after // DetectChanges is called. var addedAftereDetectChanges = context.ObjectStateManager. GetObjectStateEntries(EntityState.Added); // It should be 1 entity added. Console.WriteLine("After DetectChanges is called, " + "{0} object(s) added", addedAftereDetectChanges.Count()); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
/// <summary> /// Demostrate how to update POCO entity properties without change /// tracking proxy. /// </summary> private static void UpdatePropertyWithoutChangeTrackingProxy() { Console.WriteLine("Update properties without change tracking proxy..."); try { using (POCOChangeTrackingEntities context = new POCOChangeTrackingEntities()) { // Turn off proxy creation. context.ContextOptions.ProxyCreationEnabled = false; Department department = context.Departments. Single(d => d.Name == "Chinese"); // Retrieve the entity state entry. ObjectStateEntry entry = context.ObjectStateManager. GetObjectStateEntry(department); // It should be "Unchanged" now. Console.WriteLine("Entity State before modification: {0}", entry.State); department.Name = "New Department Name"; // It should be "Unchanged" now. Console.WriteLine("Entity State after modification: {0}", entry.State); // Detect the entity properties changes. context.DetectChanges(); // It should be "Modified" now. Console.WriteLine("Entity State after DetectChanges is called: " + "{0}", entry.State); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }