不错的东西: AutoMapper

详细信息可阅读原文:http://csharppulse.blogspot.in/2013/08/crud-operations-using-automapper-in-c_381.html


这东西可简化将模型转换为实体的代码,具体可看代码:

目前习惯写法的代码:

public ActionResult Details(int? id)
        {
            var dbContext = new MyDBDataContext();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            var user = new LearningMVC.Models.User();
            if (userDetails != null)
            {
                user.UserId = userDetails.UserId;
                user.FirstName = userDetails.FirstName;
                user.LastName = userDetails.LastName;
                user.Address = userDetails.Address;
                user.PhoneNo = userDetails.PhoneNo;
                user.EMail = userDetails.EMail;
                user.Company = userDetails.Company;
                user.Designation = userDetails.Designation;
            }
            return View(user);
        }

使用AutoMap后可这样写:

public ActionResult Details(int? id)
        {
            var dbContext = new MyDBDataContext();
            Mapper.CreateMap<LearningMVC.User, LearningMVC.Models.User>();
            var userDetails = dbContext.Users.FirstOrDefault(userId => userId.UserId == id);
            LearningMVC.Models.User user = Mapper.Map<LearningMVC.User, LearningMVC.Models.User>(userDetails);
            return View(user);
        }


你可能感兴趣的:(C#)