【问题标题】:Handling unchanged/not relevant relationships when auto-mapping from DTO to entity model从 DTO 自动映射到实体模型时处理未更改/不相关的关系
【发布时间】:2014-02-28 12:19:37
【问题描述】:

我在尝试更新具有我在前端不关心的关系的实体时遇到了一个烦人的问题。 问题是,当自动映射器创建我的项目时,默认构造函数将关系设置为一个空列表(应该为空),这在 EF 尝试保存它时会导致问题,因为现在它认为它应该删除现有实体的关系。

我认为这是许多人都遇到过的问题,但谷歌似乎并不这么认为。我是否以错误的方式处理这个问题?从 DTO 映射到实体模型时如何维护实体关系?

// 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;}
}

控制器动作

[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);
}

【问题讨论】:

    标签: c# asp.net-mvc entity-framework automapper dto


    【解决方案1】:

    有两种方法可以解决这个问题:

    您也可以在 AutoMapper 映射后将关系设置为 null

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

    或者您可以创建一个始终将其设置为 null 的自定义自动映射器配置文件:

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

    如果这是您唯一需要的地方,您将使用第一种方法。如果总是这样,请使用第二个

    【讨论】:

    • 与其创建配置文件,为什么不在映射配置本身中将属性设置为 null?
    • 有时简单的解决方案是最好的 :) 我在想某处可能有一些设置。
    猜你喜欢
    • 2019-01-14
    • 2018-04-29
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多