سؤال

I've run into an annoying problem when trying to update an entity that has a relationship which I don't care about in the frontend. The problem is that when automapper creates my Item the default constructor sets the relationship to an empty list (should be null) which causes problems when EF is trying to save it, because now it thinks that it should delete the relationship the existing entity has.

I was thinking that this is a problem many have had, but google didn't seem to think so. Am I approaching this in a wrong way? How do you maintain your entity relationships when mapping from DTO to entity model?

Classes

// normal code first POCO class
public class Item
{
    public Item()
    {
        Others = new List<Other>();
    }

    public int Id {get; set;}
    public virtual ICollection<Other> Others {get; set;}
}

// my DTO
public class ItemDTO
{
    public int Id {get; set;}
}

Controller action

[HttpPost]
public void PostAction(ItemDTO dto)
{
    var item = Mapper.Map<Item>(dto);
    // The problem here is that item.Others.Count is 0, should be null
    // so EF thinks it needs to delete the relationships
    _repo.Update(item);
}
هل كانت مفيدة؟

المحلول

There's two ways you can go about this:

Either you could just set the relation to null after AutoMapper has mapped it:

[HttpPost]
public void PostAction(ItemDTO dto)
{
    var poco = Mapper.Map<Item>(dto);
    poco.Others = null;
    _repo.Update(poco);
}

Or you could create a custom automapper profile that always sets it to null:

public class ItemMap : Profile
{
    protected override void Configure()
    {
        CreateMap<Item, Listing>().ForMember(d => d.Others, o => o.UseValue(null));
    }
}

You'd use the first method if that's the only place you want it. Use the second one if it's always the case

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top