AutoMapper mapping int[] or List<int> from ViewModel to a List<Type> in Domain Model
I'm new to AutoMapper and I've been reading and reading questions around here but I'm not quite able to figure out what looks like a very trivial question.
First my classes, then the question(s):
GatewayModel.cs
public class Gateway
{
public int GatewayID { get; set; }
public List<Category> Categories { get; set; }
public ContentType ContentType { get; set; }
// ...
}
public class Category
{
public int ID { get; set; }
开发者_StackOverflow社区 public int Name { get; set; }
public Category() { }
public Category( int id ) { ID = id; }
public Category( int id, string name ) { ID = id; Name = name; }
}
public class ContentType
{
public int ID { get; set; }
public int Name { get; set; }
public ContentType() { }
public ContentType( int id ) { ID = id; }
public ContentType( int id, string name ) { ID = id; Name = name; }
}
GatewayViewModel.cs
public class GatewayViewModel
{
public int GatewayID { get; set; }
public int ContentTypeID { get; set; }
public int[] CategoryID { get; set; }
// or public List<int> CategoryID { get; set; }
// ...
}
From what I've been reading all day this is what I have figured out so far. I don't know how to map the int[] (or List if it needs be) from the ViewModel to the List in the Model.
Global.asax.cs
Mapper.CreateMap<Gateway, GatewayViewModel>();
Mapper.CreateMap<GatewayViewModel, Gateway>()
.ForMember( dest => dest.ContentType, opt => opt.MapFrom( src => new ContentType( src.ContentTypeID ) ) )
.ForMember( /* NO IDEA ;) */ );
Basically I need to map all int[] CategoryID items from the ViewModel to the ID propery of the List Categories type in the Model. For the reverse mapping I need to map all ID's from the Category type to my int[] (or List) CategoryID but I think I have that figured out (haven't gotten there yet). If I need to do something similar for the reverse mapping, please let me know.
FYI, my int[] CategoryID in my ViewModel is bonded to a SelectList in my View.
I wish the CodePlex project site for AutoMapper had a more complete documentation but I'm happy they at least have what they have.
Thank you!
You could do the following:
Mapper
.CreateMap<int, Category>()
.ForMember(
dest => dest.ID,
opt => opt.MapFrom(src => src)
);
Mapper
.CreateMap<GatewayViewModel, Gateway>()
.ForMember(
dest => dest.Categories,
opt => opt.MapFrom(src => src.CategoryID)
);
var source = new GatewayViewModel
{
CategoryID = new[] { 1, 2, 3 }
};
Gateway dst = Mapper.Map<GatewayViewModel, Gateway>(source);
Obviously you cannot map the Name
property from the view model to the model because it is not present.
精彩评论