【发布时间】: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 时,我收到了错误消息。
有什么线索吗?
【问题讨论】:
-
我试过但得到错误缺少类型映射配置或不支持的映射。解析器完成访问所有域模型属性并开始访问下面的虚拟映射。在访问“BackInStockSubscriptions”时,上述问题正在发生。
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; }我还需要做什么吗? -
你能把这个放在你的问题中吗?很难从评论中阅读代码。
-
嗨 abatishchev,我已经编辑了我的问题。请立即检查。
标签: c# .net entity-framework automapper