Reputation: 253
Can I track changes of child entities using ef 5?
Example:
Domain objects: Book (one to many) Page
var oldBook = context.Books.Include("Pages");
context.Entry(oldBook).CurrentValues.SetValues(updatedBook);
This code will update simple properties of the old book object with values of simple properties from updatedBook object.
It there any way to track children collection?(Pages in this case). Or any best practices how to do it?
Upvotes: 1
Views: 4218
Reputation:
Your questions is a bit ambiguous.
Can I track changes of child entities using ef 5?
Of course, unless you explicitly disable change tracking using IQueryable.AsNoTracking()
or MergeOption.NoTracking
then you can track changes of any entity attached to the DBContext
ObjectStateManager
.
If you are really asking if there's a function where you can do this:
context.Entry(oldBook).CurrentValues.SetValues(updatedBook);
And have the current values of the entire object graph -- where oldbook is the root -- set to the updated values of the updatedBook object graph then, no.
You have to loop through and call context.Entry(oldPage).CurrentValues.SetValues(updatedPage)
for each page you wished to update.
I take it that you are in a disconnected scenario where you can't just pull the entities from the database and use automatic change tracking and set the modified values directly on the tracked entities, otherwise you could just use a single object graph attached to the context instead of working with two instances (ie oldbook, updated book).
If you already have a detached modified object graph that you need to work with an alternative to retrieving the entity from the db and using SetValues()
is to attach the entities to the context as modified. You still need to loop through and do the same for all entities in the object graph.
context.Entry(updatedBook).State = EntityState.Modified;
foreach(var p in updatedBook.Pages) context.Entry(p).State = EntityState.Modified;
context.SaveChanges();
Upvotes: 4