Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
586 views
in Technique[技术] by (71.8m points)

c# - Mapping a DTO to an Entity with Automapper

I have an Entity Framework POCO with the following structure.

public class Entity
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}

I've created a Data Transfer Object for this entity to be used by my views.

public class EntityDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Now, I have the following mapping code in my Global.asax file.

Mapper.CreateMap<Entity, EntityDto>();
Mapper.CreateMap<EntityDto, Entity>(); // not sure whether I need this as well?

Everything is working fine, I pass the DTO to my views OK and I can create a new instance of Entity from my EntityDto model. The problem arises when I try to edit my Entity; I'm aware this is down to AutoMapper losing the Entity Key that EF creates to track changes to the object, but having read through a few sources there doesn't seem to be a definitive solution. Here is the action I'm using to edit my entity.

public ActionResult EditEntity(EntityDto model)
{
    var entity = context.Entities.Single(e => e.Id == model.Id);
    entity = Mapper.Map<EntityDto, Entity>(model); // this loses the Entity Key stuff
    context.SaveChanges();

    return View(model);
}

Now, what do I do to solve this? Can I:

  1. Somehow tell AutoMapper to .Ignore() the Entity Key properties?
  2. Get AutoMapper to copy out the Entity Key properties?
  3. .Attach() my mapped Entity and set the state to modified?

Any help always appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try passing entity as a second parameter to your mapping.

entity = Mapper.Map<EntityDto, Entity>(model, entity);

Otherwise, your entity instance is overwritten with a new instance, and you lose the entity created in the first line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...