AutoMapper 初次使用心得

來源:互聯網
上載者:User

標籤:

本例以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="[email protected]",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 初次使用心得

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.