C# AutoMapper:手动设置属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15277904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AutoMapper: manually set property
提问by user2145393
I am using AutoMapper to map from flat DataObjects to fat BusinessObjects and vice versa. I noticed that mapping from DataObjects to BusinessObjects takes extra time because of change notification of the BusinessObjects (implements INotifyPropertyChanged with custom validation, etc).
我正在使用 AutoMapper 从平面 DataObjects 映射到胖 BusinessObjects,反之亦然。我注意到从 DataObjects 映射到 BusinessObjects 需要额外的时间,因为 BusinessObjects 的更改通知(使用自定义验证实现 INotifyPropertyChanged 等)。
Because I normally don't need change notification during mapping, I'd like to turn it off. So I added a property "IsPropertyChangedEnabled". If this property is set to false, no NotifyPropertyChanged event is not raised and time is saved.
因为我通常在映射期间不需要更改通知,所以我想将其关闭。所以我添加了一个属性“IsPropertyChangedEnabled”。如果此属性设置为 false,则不会引发 NotifyPropertyChanged 事件并节省时间。
Question:
题:
Can I tell AutoMapper to set this property to false at the very beginning of the mapping process? If so, how?
我可以告诉 AutoMapper 在映射过程的一开始就将此属性设置为 false 吗?如果是这样,如何?
Thank you!
谢谢!
采纳答案by Sergey Berezovskiy
Use BeforeMap
method to set property value before mapping process:
使用BeforeMap
方法在映射过程之前设置属性值:
Mapper.CreateMap<Source, Destination>()
.BeforeMap((s, d) => d.IsPropertyChangedEnabled = false );
回答by Chinjoo
From what I understand from the description is that you don't want to fire the property change notification while fetch data from db using the DO and filling the BO.
从我从描述中了解到的是,您不希望在使用 DO 从 db 获取数据并填充 BO 时触发属性更改通知。
One possible solution for this would be to have a base class for all BO having two major functionality, 1. Property - IsLoaded which will be set by the mapper after the data is loaded and 2. INotifyPropertyChange implementation and a method to wrap the RaisePropertyChange publisher to check the IsLoaded property and raise the event based on that.
一种可能的解决方案是为所有具有两个主要功能的 BO 提供一个基类,1. 属性 - IsLoaded,它将在数据加载后由映射器设置,2. INotifyPropertyChange 实现和包装 RaisePropertyChange 发布者的方法检查 IsLoaded 属性并基于此引发事件。
回答by Twisted
You can also use ForMember() which has the added benefit of passing the standard unit test of Mapper.AssertConfigurationIsValid() when the properties being set to values are not in the source object.
您还可以使用 ForMember(),它具有通过 Mapper.AssertConfigurationIsValid() 的标准单元测试的额外好处,当设置为值的属性不在源对象中时。
here's an example
这是一个例子
Mapper.CreateMap<ClientData, GenerateClientLetterCommand>()
.ForMember(x => x.Id, opt => opt.MapFrom( o => Guid.NewGuid()))
.ForMember(x => x.Created, opt => opt.MapFrom( o => DateTime.Now));