ASP.NET MVC и AutoMapper (заполнение модели представления из объектов родительского и дочернего доменов)

У меня есть следующие объекты домена:

public class ComponentType
{
    public int ComponentTypeID { get; set; }
    public string Component_Type { get; set; }
    public string ComponentDesc { get; set; }
}

public class AffiliateComponentType
{
    public int AffiliateComponentID { get; set; }
    public int AffiliateID { get; set; }
    public ComponentType ComponentType { get; set; }
    public bool MandatoryComponent { get; set; }
    public bool CanBeBookedStandalone { get; set; }
    public int PreferenceOrder { get; set; }
}

Я получу СПИСОК AffiliateComponentType из БД, используя NHibernate. Теперь мне нужно заполнить СПИСОК AffiliateComponentTypeView (модель представления) из СПИСКА объекта домена AffiliateComponentType. Как я могу добиться этого с помощью AutoMapper?

[Serializable]
public class AffiliateComponentTypeView
{
    public int ComponentTypeID { get; set; }
    public string Component_Type { get; set; }
    public string ComponentDesc { get; set; }
    public bool MandatoryComponent { get; set; }
    public bool CanBeBookedStandalone { get; set; }
    public int PreferenceOrder { get; set; }
}

person Alex    schedule 07.02.2011    source источник


Ответы (2)


Следующее сопоставление должно выполнять работу по сглаживанию вашей модели:

Mapper
    .CreateMap<AffiliateComponentType, AffiliateComponentTypeView>()
    .ForMember(
        dest => dest.ComponentTypeID,
        opt => opt.MapFrom(src => src.ComponentType.ComponentTypeID)
    )
    .ForMember(
        dest => dest.Component_Type,
        opt => opt.MapFrom(src => src.ComponentType.Component_Type)
    )
    .ForMember(
        dest => dest.ComponentDesc,
        opt => opt.MapFrom(src => src.ComponentType.ComponentDesc)
    );

и если вы изменили свою модель представления следующим образом:

[Serializable]
public class AffiliateComponentTypeView
{
    public int ComponentTypeComponentTypeID { get; set; }
    public string ComponentTypeComponent_Type { get; set; }
    public string ComponentTypeComponentDesc { get; set; }
    public bool MandatoryComponent { get; set; }
    public bool CanBeBookedStandalone { get; set; }
    public int PreferenceOrder { get; set; }
}

Выравнивание будет выполняться AutoMapper автоматически с использованием стандартных соглашений, поэтому все, что вам нужно, это:

Mapper.CreateMap<AffiliateComponentType, AffiliateComponentTypeView>();

Просто будет небольшая проблема со свойством Component_Type, поскольку оно противоречит соглашению об именах AutoMapper по умолчанию, поэтому вам может потребоваться переименовать его.

После того, как вы определили сопоставление, вы можете сопоставить:

IEnumerable<AffiliateComponentType> source = ...
IEnumerable<AffiliateComponentTypeView> dest = Mapper.Map<IEnumerable<AffiliateComponentType>, IEnumerable<AffiliateComponentTypeView>>(source);
person Darin Dimitrov    schedule 07.02.2011

Где-то в вашем приложении у вас будет блок кода, который настраивает AutoMapper, поэтому я предполагаю, что у вас будет блок, который выглядит так:

Mapper.CreateMap<ComponentType, AffiliateComponentTypeView>();
Mapper.CreateMap<AffiliateComponentType, AffiliateComponentTypeView>();

Затем, как только вы вернете свою модель из nHibernate, вы создадите свою модель представления следующим образом:

var model = Session.Load<AffiliateComponentType>(id);
var viewModel = Mapper.Map<AffiliateComponentType, 
    AffiliateComponentTypeView>(model);
if (model.ComponentType != null)
    Mapper.Map(model.ComponentType, viewModel);

Надеюсь, это приведет вас туда, куда вы направляетесь!

person JMP    schedule 07.02.2011