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?

有帮助吗?

解决方案

try calling context.ChangeTracker.DetectChanges()

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top