I am trying to use the DbEntityEntry.CurrentValues.SetValues() method to facilitate updating an existing entity with values from a non-entity DTO (see: http://blogs.msdn.com/b/adonet/archive/2011/01/30/using-dbcontext-in-ef-feature-ctp5-part-5-working-with-property-values.aspx)
I'm having trouble removing the dependency on DbEntityEntry though (for mocking, testing). Here is an example of what I would like to do:
var entity = dbSet.Find(dto.Id);
var entry = context.Entry(entity);
entry.CurrentValues.SetValues(dto);
context.SaveChanges();
I've also considered:
EntityType entity = new EntityType() { Id = dto.Id };
context.Attach(entity);
var entry = context.Entry(entity);
entry.CurrentValues.SetValues(entity);
context.SaveChanges();
From what I've been able to fin开发者_如何学God both seem reasonable when working with an actual DbContext, but when I abstract the context to an IMyContext I lose the capability to get a DbEntityEntry for an entity, thus losing the SetValues option.
Is there any way to work around this issue, or do I need to bite the bullet and manually set modified properties on the entity from the DTO (potentially a lot of boilerplate for entities with many properties)?
(I'm fairly new to EF and this is my first StackOverflow question, so please be gentle)
If you have never used it before, this would be a great use for AutoMapper (also available via NuGet). I am unaware of how to solve your IMyContext issue and would also resort to mapping the properties. But instead of doing so manually, I would allow AutoMapper to do the heavy lifting.
精彩评论