標籤:最佳化 model轉換 automapper
在引入了entity framework 之後,系統有了一種新的需求,即對Viewmodel 和model之間的相互轉換。
這之間有各種境界。今天拿出來品味一下。
1 用automapper
方法很簡單。①添加對automapper的引用
② 在引用的時候,建立兩個實體之間的映射關係。我們要做的只是將要映射的兩個類型告訴AutoMapper(調用Mapper類的Static方法CreateMap並傳入要映射的類型):
<span style="font-family:KaiTi_GB2312;font-size:18px;"> Mapper.CreateMap<StudentViewModel, BasicStudentEntity>();</span>
③實行轉換
<span style="font-family:KaiTi_GB2312;font-size:18px;"> BasicStudentEntity enStudent = Mapper.Map<StudentViewModel, BasicStudentEntity>(student);</span>
如果studentviewmodel中有值為空白的屬性,AutoMapper在映射的時候會把BasicStudentEntity中的相應屬性也置為空白。當然我所說的是一種最為簡單的使用方式。最簡單,但是其可用範圍也是最小。要求結構完全一致,且欄位名也完全相同。很多情況下由於viewmodel 中的一些欄位和model的不完全一致。導致我們使用這樣的方式,非常不靈活。
其實automapper還有一種使用方式,即欄位名不必完全一致。(但是其意義應一致),這樣的話我們可以定義類型間的簡易對應規則。
<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>
但是即便是這樣的話,還是不能解決我的另一個問題。那就是當StudentViewModel比BasicStudentEntity 中的欄位要多(意義也不一致)的情況下,無法進行轉換。
2自訂
這時候我們想到了我們自己轉換寫的自訂方法。
<span style="font-family:KaiTi_GB2312;font-size:18px;"> #region 3.0.0 學生管理公用方法 將view 轉換成model(basicStudent) /// <summary> /// 學生管理公用方法 將view 轉換成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>
自己的方法還是用著方便一點。如果是底層封裝的話,是不是再加上泛型就可以大家共同調用了。這部分沒有自己實踐。僅供交流。
實體類型的轉換? Automapper OR 自訂