Automapper with different name
Installing using nuget
Classes
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UsingAutoMapper.Models
{
public class Scope
{
public int ScopeId { get; set; }
public string ScopeName { get; set; }
public string ScopeDisplay1 { get; set; }
public
List<TScopeType> ScopeTypes1 { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace UsingAutoMapper.Models
{
public class ScopeViewModel
{
public int ScopeId { get; set; }
public string ScopeName { get; set; }
/// <summary>
/// Id + Name
/// </summary>
public string ScopeDisplay { get; set; }
public
List<TScopeTypeViewModel> ScopeTypes { get; set; }
}
}
// Is different
public
List<TScopeType> ScopeTypes1 { get; set; }
Calling function
We need to apply config
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ScopeViewModel, Scope>().
ForMember(de =>
de.ScopeTypes1
, opts => opts.MapFrom(src =>
src.ScopeTypes));
});
Whole code
private void
UseAutoMapperWithListDifferentName()
{
ScopeViewModel model = new ScopeViewModel()
{
ScopeId = 1,
ScopeName = "ScopeOne",
ScopeTypes = new
List<TScopeTypeViewModel>() {
new
TScopeTypeViewModel(){ScopeTypeId=1,ScopeTypeName="ScopeTypeName" },
new
TScopeTypeViewModel(){ScopeTypeId=2,ScopeTypeName="ScopeTypeName2" },
}
};
//
model.ScopeDisplay = model.ScopeId + " - " + model.ScopeName;
Scope scope = new Scope();
// model = scope;
Mapper.Initialize(cfg =>
{
cfg.CreateMap<ScopeViewModel, Scope>().
ForMember(de =>
de.ScopeTypes1, opts => opts.MapFrom(src => src.ScopeTypes));
});
var sourceWithMapper =
Mapper.Map<Scope>(model);
}
0 comments:
Post a Comment