AutoMapper with Entity Framework causes EntityState = Detached

3132 views
Skip to first unread message

Sam

unread,
Mar 30, 2010, 3:27:35 PM3/30/10
to AutoMapper-users
Hello,

I am trying to use Automapper with Entity Framework to map from DTO
objects back to database entities. I am encountering a problem with
the following approach:

MyDTO dto = new MyDTO();
dto.Name = "Nick";

using (MyEntityContainer ec = new MyEntityContainer()) {
MyEntity entity = ec.MyEntities.Single(s => s.Id == 1); // retrieve
entity from data store

Mapper.CreateMap<MyDTO, MyEntity>();
entity = Mapper.Map<MyDTO, NyEntity>(dto);

ec.SaveChanges();
}

This approach will correctly change the Name property of entity to
"Nick" but in the process, the EntityState gets changed to Detached,
which results in the SaveChanges() not to save the entity object.

A manual mapping without AutoMapper, setting entity.Name = dto.Name
will result in the EntityState to get set to Modified (expected
behaviour), which results in a following SaveChanges to correctly save
the object. I could of course do an Attach of the entity object after
mapping it up with AutoMapper, but I don't see why this would be
necessary. Is there some workaround for this, or is this expected
behaviour due to the internals of AutoMapper?

Setting .ForMember to Ignore on EntityState and EntityKey does not
work.

Jimmy Bogard

unread,
Mar 30, 2010, 6:48:33 PM3/30/10
to automapp...@googlegroups.com
Try mapping to an existing object:

Mapper.Map<MyDTO, NyEntity>(dto, entity);

And keep the Ignore()'s in place.

Thanks,

Jimmy


--
You received this message because you are subscribed to the Google Groups "AutoMapper-users" group.
To post to this group, send email to automapp...@googlegroups.com.
To unsubscribe from this group, send email to automapper-use...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/automapper-users?hl=en.


Sam

unread,
Mar 31, 2010, 2:48:38 AM3/31/10
to AutoMapper-users
Thanks Jimmy,

this seems to have worked out beautifully.

Actually, there was no need to keep the .Ignores because the DTO
doesn't have the EntityState and EntityKey properties.

Cheers, and happy easter :)

On Mar 31, 12:48 am, Jimmy Bogard <jimmy.bog...@gmail.com> wrote:
> Try mapping to an existing object:
>
> Mapper.Map<MyDTO, NyEntity>(dto, entity);
>
> And keep the Ignore()'s in place.
>
> Thanks,
>
> Jimmy
>

> > automapper-use...@googlegroups.com<automapper-users%2Bunsu...@googlegroups.com>

Reply all
Reply to author
Forward
0 new messages