我正在尝试映射两个相同类型的对象。我想做的是使用AutoMapper来加载源对象中具有Null
值的所有属性,并保留目标对象中的现有值。
我试过在我的“仓库”中使用它,但它似乎不起作用。
Mapper.CreateMap<TEntity, TEntity>().ForAllMembers(p => p.Condition(c => !c.IsSourceValueNull));
可能的问题是什么?
发布于 2012-09-21 10:27:59
很有趣,但您最初的尝试应该是可行的。下面的测试是绿色的:
using AutoMapper;
using NUnit.Framework;
namespace Tests.UI
{
[TestFixture]
class AutomapperTests
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Foo { get; set; }
}
[Test]
public void TestNullIgnore()
{
Mapper.CreateMap<Person, Person>()
.ForAllMembers(opt => opt.Condition(srs => !srs.IsSourceValueNull));
var sourcePerson = new Person
{
FirstName = "Bill",
LastName = "Gates",
Foo = null
};
var destinationPerson = new Person
{
FirstName = "",
LastName = "",
Foo = 1
};
Mapper.Map(sourcePerson, destinationPerson);
Assert.That(destinationPerson,Is.Not.Null);
Assert.That(destinationPerson.Foo,Is.EqualTo(1));
}
}
}
发布于 2017-07-14 16:13:08
使用3个参数的Condition
重载让您将表达式等同于示例p.Condition(c => !c.IsSourceValueNull)
方法签名:
void Condition(Func<TSource, TDestination, TMember, bool> condition
等价表达式:
CreateMap<TSource, TDestination>.ForAllMembers(
opt => opt.Condition((src, dest, sourceMember) => sourceMember != null));
发布于 2012-09-20 22:13:51
到目前为止,我已经解决了这个问题。
foreach (var propertyName in entity.GetType().GetProperties().Where(p=>!p.PropertyType.IsGenericType).Select(p=>p.Name))
{
var value = entity.GetType().GetProperty(propertyName).GetValue(entity, null);
if (value != null)
oldEntry.GetType().GetProperty(propertyName).SetValue(oldEntry, value, null);
}
但仍希望找到使用AutoMapper的解决方案
https://stackoverflow.com/questions/12514084
复制相似问题