實(shí)體類型的轉(zhuǎn)換? Automapper OR 自定義
來源:程序員人生 發(fā)布時(shí)間:2015-05-28 09:07:27 閱讀次數(shù):3584次
在引入了entity framework 以后,系統(tǒng)有了1種新的需求,即對Viewmodel 和model之間的相互轉(zhuǎn)換。
這之間有各種境地。今天拿出來品味1下。
1 用automapper
方法很簡單。①添加對automapper的援用

② 在援用的時(shí)候,創(chuàng)建兩個(gè)實(shí)體之間的映照關(guān)系。我們要做的只是將要映照的兩個(gè)類型告知AutoMapper(調(diào)用Mapper類的Static方法CreateMap并傳入要映照的類型):
<span style="font-family:KaiTi_GB2312;font-size:18px;"> Mapper.CreateMap<StudentViewModel, BasicStudentEntity>();</span>
③實(shí)行轉(zhuǎn)換
<span style="font-family:KaiTi_GB2312;font-size:18px;"> BasicStudentEntity enStudent = Mapper.Map<StudentViewModel, BasicStudentEntity>(student);</span>
如果studentviewmodel中有值為空的屬性,AutoMapper在映照的時(shí)候會把BasicStudentEntity中的相應(yīng)屬性也置為空。固然我所說的是1種最為簡單的使用方式。最簡單,但是其可用范圍也是最小。要求結(jié)構(gòu)完全1致,且字段名也完全相同。很多情況下由于viewmodel 中的1些字段和model的不完全1致。致使我們使用這樣的方式,非常不靈活。
其實(shí)automapper還有1種使用情況,即字段名沒必要完全1致。(但是其意義應(yīng)1致),這樣的話我們可以定義類型間的簡單映照規(guī)則。
<span style="font-family:KaiTi_GB2312;font-size:18px;">1. var map = Mapper.CreateMap<StudentViewModel,BasicStudentEntity>();
2. map.ForMember(d => d.Name, opt => opt.MapFrom(s => s.SchoolName));
</span>
但是即使是這樣的話,還是不能解決我的另外一個(gè)問題。那就是當(dāng)StudentViewModel比BasicStudentEntity 中的字段要多(意義也不1致)的情況下,沒法進(jìn)行轉(zhuǎn)換。
2自定義
這時(shí)候候我們想到了我們自己轉(zhuǎn)換寫的自定義方法。
<span style="font-family:KaiTi_GB2312;font-size:18px;"> #region 3.0.0 學(xué)生管理公共方法 將view 轉(zhuǎn)換成model(basicStudent)
/// <summary>
/// 學(xué)生管理公共方法 將view 轉(zhuǎn)換成model(basicStudent)
/// </summary>
/// <param name="enstudentList"></param>
/// <returns></returns>
public List<BasicStudentEntity> ChangeViewToBasicstudentModel(List<StudentViewModel> enstudentList)
{
List<BasicStudentEntity> studentList = new List<BasicStudentEntity>();
foreach (var item in enstudentList)
{
BasicStudentEntity student = new BasicStudentEntity()
{
StudentID = item.StudentID,
StudentNo = item.StudentNo,
UserCode = item.UserCode,
EntryPartyTime = item.EntryPartyTime,
Speciality = item.Speciality,
HealthCondition = item.HealthCondition,
ExamineeNumber = item.ExamineeNumber,
FatherName = item.FatherName,
MotherName = item.MotherName,
FatherPhone = item.FatherPhone,
MotherPhone = item.MotherName,
TrainDestination = item.TrainDestination,
Note = item.Note,
Operator = item.Operator,
TimeStamp = item.TimeStamp,
CreditCardNo = item.CreditCardNo,
Name = item.Name,
Sex = item.Sex,
PoliticalStatus = item.PoliticalStatus,
PreviousName = item.PreviousName,
Email = item.Email,
CellPhoneNumber = item.CellPhoneNumber,
HomeTelephone = item.HomeTelephone,
BirthPlace = item.BirthPlace,
HomeAddress = item.HomeAddress,
Nation = item.Nation,
RoomID = item.RoomID,
DirectionID = item.DirectionID,
ClassID = item.ClassID
};
studentList.Add(student);
}
return studentList;
}
#endregion
</span>
自己的方法還是用著方便1點(diǎn)。如果是底層封裝的話,是否是再加上泛型就能夠大家共同調(diào)用了。這部份沒有自己實(shí)踐。僅供交換。
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈