2011-02-07 56 views
3

我有以下doimain对象: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; } 
} 

我会使用NHibernate从数据库得到AffiliateComponentType的列表。现在,我必须从AffiliateComponentType域对象的LIST填充AffiliateComponentTypeView(View Model)列表。我如何使用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; } 
} 

回答

2

下映射应该做的flattening your model工作:

​​

,如果你修改了您的视图模型是这样的:

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

有wil我只是Component_Type属性的一个小问题,因为它与AutoMapper的默认命名约定相冲突,所以您可能需要重命名它。

一旦你定义了你可以映射的映射:

IEnumerable<AffiliateComponentType> source = ... 
IEnumerable<AffiliateComponentTypeView> dest = Mapper.Map<IEnumerable<AffiliateComponentType>, IEnumerable<AffiliateComponentTypeView>>(source); 
+0

感谢达林。我使用了你建议的第一种方法。非常感谢... – Alex 2011-02-07 18:30:50

1

某处在您的应用程序,你就会有该配置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); 

希望这可以让你在那里你的方向!

相关问题