2

我有一个平面 POCO 实体和一个结构化视图模型(用于使用自定义 EditorFor 助手呈现表单)。

Automapper 2 中有没有更简单的方法来做这样的事情:

cfg.CreateMap<TelcoDemand, TelcoDemandViewModel>()
.ForMember(d => d.Person, opt => opt.ResolveUsing(s => new PersonViewModel
    {
        FirstName = s.PersonFirstName,
        LastName = s.PersonLastName,
        Phone = s.PersonPhone,
        Email = s.PersonEmail
    }))
.ForMember(d => d.AddressContact, opt => opt.ResolveUsing(s => new AddressViewModel
    {
        City = s.AddressContactCity,
        HouseNumber = s.AddressContactHouseNumber,
        Street = s.AddressContactStreet,
        Zip = s.AddressContactZip
    }))
.ForMember(d => d.AddressCourier, opt => opt.ResolveUsing(s => new AddressViewModel
    {
        City = s.AddressCourierCity,
        HouseNumber = s.AddressCourierHouseNumber,
        Street = s.AddressCourierStreet,
        Zip = s.AddressCourierZip
    }))
.ForMember(d => d.Address, opt => opt.ResolveUsing(s => new AddressViewModel
    {
        City = s.AddressCity,
        HouseNumber = s.AddressHouseNumber,
        Street = s.AddressStreet,
        Zip = s.AddressZip
    }))

我想要实现的是将人员和地址字段展开为视图模型,然后使用 EditorFor 进行渲染。

将其展平回数据库效果很好,但我无法按照惯例让展平工作......

编辑

我还有一个在这里使用的 IgnoreAllUnexisting 扩展,它是这样实现的:

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
    var sourceType = typeof(TSource);
    var destinationType = typeof(TDestination);
    var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType == sourceType && x.DestinationType == destinationType);
    foreach (var property in existingMaps.GetUnmappedPropertyNames())
    {
        expression.ForMember(property, opt => opt.Ignore());
    }
    expression.ForAllMembers(opt => opt.Condition(src => !src.IsSourceValueNull));
    return expression;
}

无论如何,我也尝试了没有那个扩展名,结果是一样的——复杂类型中的一堆空值。

4

0 回答 0