gpt4 book ai didi

ASP.NET MVC 和 AutoMapper(从父域对象和子域对象填充 View 模型)

转载 作者:行者123 更新时间:2023-12-02 12:01:07 26 4
gpt4 key购买 nike

我有以下域对象:

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; }
}

我将使用 NHibernate 从数据库获取 AffiliateComponentType 的列表。现在,我必须从 AffiliateComponentType 域对象的列表中填充 AffiliateComponentTypeView( View 模型)的列表。如何使用 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; }
}

最佳答案

以下映射应该完成 flattening your model 的工作:

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)
);

如果您像这样修改了 View 模型:

[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);

关于ASP.NET MVC 和 AutoMapper(从父域对象和子域对象填充 View 模型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4923841/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com