0

When a call is made to the SaveChanges() method of an context, the relationships on the other side of the change are automatically updated.

For instance if I had a teacher mrX with a virtual ICollection of students including littleJohnny

mrX.Students.Remove(littleJohnny);
Debug.Assert(littleJohnny.Teacher!=null); //assert should pass
context.SaveChanges();
Debug.Assert(littleJohnny.Teacher==null); //assert should pass

mrX.Students.Add(littleJohnny);
context.SaveChanges();//revert to previous state

littleJohnny.Teacher=null;
Debug.Assert(mrX.Students.Contains(littleJohnny)); //assert should pass
context.SaveChanges();
Debug.Assert(!mrX.Students.Contains(littleJohnny)); //assert should pass
  1. Is there any way to update such relationships without saving the data to the database in Entity Framework 4.3 and 5.0 ?

  2. In a different scenario, If I have a ViewModel which maps to the above entities, is there a simple way I can copy this EF behavior -> that is, track the relationships and update the relationships on calling a method?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Brent
  • 4,611
  • 4
  • 38
  • 55
  • Couple of Questions: 1. ARe you using EF Code-first? 2. When you ViewModel, are you talking WPF or Silverlight? – Alastair Pitts Feb 12 '13 at 03:00
  • Sorry - should have specified, Yes I am using code first. As for view model I predominantly use mvvm and WPF, but really b view model I mean something mapped across from the entities, such as using Automapper onto a POCO – Brent Feb 12 '13 at 04:39

1 Answers1

1

try calling context.ChangeTracker.DetectChanges()

if that doesn't work then your related entities have not been initialised correctly

qujck
  • 14,388
  • 4
  • 45
  • 74