更新:張貼在這裏的做法是不合法的SelfProfiler
作爲AutoMapper V2的已被刪除。
我會採取與Thoai類似的方法。但我會使用內置的SelfProfiler<>
類來處理地圖,然後使用Mapper.SelfConfigure
函數進行初始化。
使用這個對象作爲源:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public string GetFullName()
{
return string.Format("{0} {1}", FirstName, LastName);
}
}
而這些作爲目標:
public class UserViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class UserWithAgeViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public int Age { get; set; }
}
您可以創建這些配置文件:
public class UserViewModelProfile : SelfProfiler<User,UserViewModel>
{
protected override void DescribeConfiguration(IMappingExpression<User, UserViewModel> map)
{
//This maps by convention, so no configuration needed
}
}
public class UserWithAgeViewModelProfile : SelfProfiler<User, UserWithAgeViewModel>
{
protected override void DescribeConfiguration(IMappingExpression<User, UserWithAgeViewModel> map)
{
//This map needs a little configuration
map.ForMember(d => d.Age, o => o.MapFrom(s => DateTime.Now.Year - s.BirthDate.Year));
}
}
要在應用程序初始化,創建此類
public class AutoMapperConfiguration
{
public static void Initialize()
{
Mapper.Initialize(x=>
{
x.SelfConfigure(typeof (UserViewModel).Assembly);
// add assemblies as necessary
});
}
}
此行添加到您的Global.asax.cs文件:AutoMapperConfiguration.Initialize()
現在,您可以將您的映射類,他們對你有意義,而不是擔心一個整體映射類。
我有兩個項目。 MyApp.UI(mvc)和MyApp.Core(CLR)。 ViewModels在MyApp.UI中,而EntityModels在MyApp.Core中。問題:「放置AutoMapperXConfiguration.cs的位置」。 (mvc或clr)?要在clr中使用它,我應該將mvc項目引用到clr。所以我認爲,在MVC是合乎邏輯的? –
@AliRızaAdıyahşi這兩個項目都應該有一個映射文件。核心應該有AutoMapperCoreConfiguration,並且UI應該有AutoMapperWebConfiguration。 Web配置應該添加來自Core配置的配置文件。 – RPM1984
在每個配置類中調用'Mapper.Initialize'是否覆蓋以前的配置文件?如果是這樣,應該用什麼來代替Initialize? – Cody