【问题标题】:Updating existing domain model using AutoMapper sets NULL使用 AutoMapper 更新现有域模型设置 NULL
【发布时间】:2015-01-27 18:29:47
【问题描述】:

我有下面的 viewmodel,它与域模型相同(但包含一些额外的属性)。

public class ProductViewModel
{
    public string Name { get; set; }
    public string ShortDescription { get; set; }
    public string FullDescription { get; set; }
    public string AdminComment { get; set; }
}

从上面看,我只使用了我的视图页面中的一些属性。

当我使用 Automapper 来映射我现有的模型时,我的所有 viewmodel 字段都被映射到 domainmodel 字段。

Mapper.Map(productViewModel, product);

由于上述映射,所有未使用的视图模型字段(默认情况下未使用的视图模型字段具有 NULL 值)都映射到域模型。它正在用 NULL 值替换我现有的数据库数据。

有没有办法从映射中排除 NULL 和默认属性值?

注意事项:

  • 我遇到了Using Automapper to update an existing Entity POCO
  • 如果我们为排除的属性使用隐藏字段,上述问题将得到解决,因为 viewmodel 将使用隐藏字段携带数据。但我不喜欢它!
  • 我尝试了以下不起作用的代码:

    Mapper.CreateMap<ProductViewModel, Product>()
          .ForAllMembers(opt =>
               opt.Condition(srs => (!srs.IsSourceValueNull || IsDefaultValue(srs.SourceValue, srs.SourceType))));
    

编辑:

在我尝试Automapper skip null values with custom resolver 之后(感谢abatishchev)。我使用了解析器,但出现错误缺少类型映射配置或不支持的映射

我的代码sn-p:

...
public System.DateTime CreatedOnUtc { get; set; }
public System.DateTime UpdatedOnUtc { get; set; }
public virtual ICollection<BackInStockSubscription> BackInStockSubscriptions { get; set; }
public virtual ICollection<OrderItem> OrderItems { get; set; }

resolver 访问上述代码中的 BackInStockSubscriptions 时,我收到了错误消息。

有什么线索吗?

【问题讨论】:

  • 你试过stackoverflow.com/questions/20021633/…的解析器吗?
  • 我试过但得到错误缺少类型映射配置或不支持的映射。解析器完成访问所有域模型属性并开始访问下面的虚拟映射。在访问“BackInStockSubscriptions”时,上述问题正在发生。
    public System.DateTime CreatedOnUtc { get; set; } public System.DateTime UpdatedOnUtc { get; set; } public virtual ICollection&lt;BackInStockSubscription&gt; BackInStockSubscriptions { get; set; } public virtual ICollection&lt;OrderItem&gt; OrderItems { get; set; }我还需要做什么吗?
  • 你能把这个放在你的问题中吗?很难从评论中阅读代码。
  • 嗨 abatishchev,我已经编辑了我的问题。请立即检查。

标签: c# .net entity-framework automapper


【解决方案1】:

不要使用 AutoMapper 映射回您的域模型。它更复杂,有太多的边缘情况,而且它不能提供与映射读取模型相同的 ROI。

我编写了这个工具,但我从来没有这样做过。您有集合、延迟加载的实体、获取、合并、加载以及很多可能出错的事情。

只是。不。去做吧。

【讨论】:

  • 那么我们如何将viewmodel数据更新回db呢?通过按属性映射属性? (因为我有 25 个属性,所以它的过程非常冗长?) 注意:据我所知,许多用户正在使用 automapper 将视图模型数据映射到域模型。这类场景的最佳做法是什么?
  • 老实说,我真的不知道。我构建的系统是面向任务的系统,而不是“可编辑字段的巨大页面”。它只是少数几个字段,通常带有验证和副作用,我不想只是将数据从一个到另一个。我听说有人使用条件和解析器等,但我从来没有这样做过。
  • 谢谢吉米。但在我上面的情况下,你能建议我任何解决方案吗?
【解决方案2】:

我已通过将 ICollection 属性添加到 AutoMapper 中的忽略列表来解决此问题。

固定代码:

Mapper.CreateMap<ProductViewModel, Product>()
        .ForMember(dest => dest.BackInStockSubscriptions, mo => mo.Ignore())
        .ForMember(dest => dest.OrderItems, mo => mo.Ignore())            
        .ForAllMembers(c => c.IgnoreIfSourceIsNull()); //To checking NULL

【讨论】:

    猜你喜欢
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多