首页 > 代码库 > AutoMapper 初次使用心得
AutoMapper 初次使用心得
本例以asp.net webform为例:
结构:
主要代码:AutoMapperConfig 类
public class AutoMapperConfig
{
public static void RegisterAutoMapper()
{
AutoMapper.Configuration.Configure();
}
}
Configuration类:
public static void Configure()
{
Mapper.Initialize(cfg =>
{
var typeToAddProfile = Assembly.GetExecutingAssembly().GetTypes();
foreach (var item in typeToAddProfile)
{
if (item.BaseType != null && item.BaseType.Name == "Profile" && !item.BaseType.Name.Equals("Configuration"))
{
object o = Activator.CreateInstance(item);
cfg.AddProfile(o as Profile);
}
}
});
Mapper.AssertConfigurationIsValid();
}
Profiles 下 TestProfiles类:
public class TestProfiles : Profile
{
protected override void Configure()
{
CreateMap<TestModel, DTO_TestModel>();
//.ForMember(a => a.Address, b => b.MapFrom(c => c.Name));
}
}
Golbal 中:
protected void Application_Start(object sender, EventArgs e)
{
AutoMapperWeb.AutoMapperConfig.RegisterAutoMapper();
}
protected void Page_Load(object sender, EventArgs e)
{
var t1 = new List<TestModel>()
{
new TestModel(){Id=1,Name="张三",Age=25,Sex="男",Address="湖南省长沙市雨花区长房天翼未来城"},
new TestModel(){Id=1,Name="李四",Age=25,Sex="男",Address="湖南省长沙市雨花区长房天翼未来城",QQ="9375671",Email="93759671@qq.com",Phone="15725032"}
};
var list = Mapper.Map<List<TestModel>, List<DTO_TestModel>>(t1);
string str = string.Format("<div><hr/>");
foreach (var item in list)
{
str += string.Format("姓名:{0},<br/>",item.Name);
str += string.Format("家庭住址:{0},<br/>", item.Address);
str += string.Format("QQ:{0},<br/>", item.QQ);
str += string.Format("邮箱:{0}<hr/>", item.Email);
}
str += string.Format("</div>");
Response.Write(str);
Response.End();
}
AutoMapper 初次使用心得