c# - 使用 AutoMapper 设置 NULL 更新现有域模型

标签 c# .net entity-framework automapper

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

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

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

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

Mapper.Map(productViewModel, product);

由于上述映射,所有未使用的 View 模型字段(默认情况下未使用的 View 模型字段具有 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)。我使用了解析器,但出现错误缺少类型映射配置或不支持的映射

我的代码片段:

...
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 时,出现错误。

有什么线索吗?

最佳答案

不要使用 AutoMapper 映射回您的领域模型。它更复杂,边缘情况太多,而且它无法提供与映射读取模型相同的投资返回率。

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

只是。不。做吧。

关于c# - 使用 AutoMapper 设置 NULL 更新现有域模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28177503/

相关文章:

c# - 获取图像文件夹的路径

c# - 是否有将模型转换为 View 模型的快捷方式?

.net - 在 .NET 中通过 Process.Start 生成的进程会挂起线程

java - 使用外键关联的一对一映射 hibernate

c# - 有没有办法让所有 C<> 都有一个静态字段值?

c# 创建或修改文件/目录权限 : add group read permission using asp.net with mono 和 apache2

c# - 无需 wddm 1.1 即可运行 Windows 7 模拟器

c# - System.Threading.TimerCallback 仅在使用 Entity Framework 时触发一次

entity-framework - EF 4.1 RTM-EntityTypeConfiguration

c# - Getter 无体,Setter 有