当前位置: 首页 > 编程语言 > C#

AutoMapper.MapIgnoresAllNullValuedPropertiesofSourceObjectShare

时间:2023-04-11 10:52:24 C#

AutoMapper.MapIgnoresAllNullValuedPropertiesofSourceObject我正在尝试映射2个相同类型的对象。我想做的是AutoMappertoigonore源对象中所有具有Null值的属性,并保留目标对象中的现有值。我试过在我的“存储库”中使用它,但它似乎没有用。Mapper.CreateMap().ForAllMembers(p=>p.Condition(c=>!c.IsSourceValueNull));可能是什么问题呢?有趣,但您的初步尝试应该是可行的方法。以下测试是绿色的:使用AutoMapper;使用NUnit.Framework;命名空间Tests.UI{[TestFixture]classAutomapperTests{publicclassPerson{publicstringFirstName{get;放;}publicstringLastName{get;放;公共诠释?Foo{得到;放;}}[测试]publicvoidTestNullIgnore(){Mapper.CreateMap().ForAllMembers(opt=>opt.Condition(srs=>!srs.IsSourceValueNull));varsourcePerson=newPerson{FirstName="Bill",LastName="Gates",Foo=null};vardestinationPerson=newPerson{FirstName="",LastName="",Foo=1};Mapper.Map(sourcePerson,destinationPerson);Assert.That(destinationPerson,Is.Not.Null);Assert.That(destinationPerson.Foo,Is.EqualTo(1));具有3个参数的Condition重载使您可以使表达式等效于示例p.Condition(c=>!c.IsSourceValueNull):方法签名:voidCondition(Funccondition等效表达式:CreateMap.ForAllMembers(opt=>opt.Condition((src,dest,sourceMember)=>sourceMember!=null));到目前为止,我已经解决了这个问题。foreach(varpropertyNameinentity.GetType().GetProperties().Where(p=>!p.PropertyType.IsGenericType).Select(p=>p.Name)){varvalue=entity.GetType().GetProperty(propertyName).GetValue(实体,空);if(value!=null)oldEntry.GetType().GetProperty(propertyName).SetValue(oldEntry,value,null);但仍然希望找到一个使用AutoMapper的解决方案,将Marty的解决方案(有效)更进一步,这里有一个通用方法可以使其更易于使用:publicstaticUMapValidValues(Tsource,Udestination){//遍历所有字段源的,如果值不为null,则覆盖目标字段上的值。foreach(source.GetType().GetProperties().Where(p=>!p.PropertyType.IsGenericType)中的varpropertyName).Select(p=>p.Name)){varvalue=source.GetType().GetProperty(propertyName).GetValue(source,null);if(value!=null&&(value.GetType()!=typeof(DateTime)||(value.GetType()==typeof(DateTime)&&(DateTime)value!=DateTime.MinValue))){destination.GetType().GetProperty(propertyName).SetValue(目标,值,n}}返回目的地;}用法:classPerson{publicstringName{get;放;公共诠释?年龄{得到;放;}公共字符串角色{得到;放;}}Personperson=newPerson(){Name="John",Age=21,Role="Employee"};PersonupdatePerson=newPerson(){Role="Manager"};person=MapValidValues(updatePerson,person);解决方法——如果源值为null,则在目标类型[DataMember(EmitDefaultValue=false)]中添加DataMember属性将删除属性[DataContract]classPerson{[DataMember]publicstringName{get;放;}[DataMember]公共整数?年龄{得到;放;}[DataMember(EmitDefaultValue=false)]publicstringRole{get;放;}}如果Role值为null,则Role属性将被删除。以上是C#学习教程:AutoMapper.Map忽略源对象的所有Null值属性。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注。本文来自网络收集,不代表作品如涉及侵权,请点击右边联系管理员删除。如需转载请注明出处: