automapper, On Create action on the controller. Confused
I have everthing set for automapper to work. Attribute is working fine as well and properly filling DTO. My Controller Create Action looks like below
[HttpPost]
[AutoMap(typeof(User), typeof(UserCreateDTO))]
public ActionResult Create(User user)
{
if (ModelState.IsValid)
{
_repository.Create(user);
return RedirectToAction("Details", new { id = user.UserId });
}
return View("Edit", user);
}
I have DataAnnotation set on User object which is my Entity object and is passed to repository which is interface via implementation and using User object everywhere.
What I want to do is like below using same above code.
[HttpPost]
[AutoMap(typeof(User), typeof(UserCreateDTO))]
public ActionResult Create(UserCreateDTO userdto)
{
if (ModelState.IsValid)开发者_运维知识库
{
_repository.Create(userdto);
return RedirectToAction("Details", new { id = userdto.UserId });
}
return View("Edit", userdto);
}
Question: My DataAnnotation are now on UserCreateDTO to limit what I want to validate. Once validation passed than there is problem which is when I pass userdto to Create method which not allowing me as User object is in the interface like below
public interface IUserRepository
{
IQueryable<User> GetAllUsers();
User GetUserById(Guid id);
void Create(User user);
User Edit(User user);
void Delete(User user);
void Save();
}
I can not change all the code to replace UserCreateDTO in Interface and Repository and What if I have UserEditDTO/UserShowDTO. How I solve this problem?. I have explained as much as possible.
Why don't you map back to a user object before calling Create? You don't need to use the attributes. You can call Map directly.
Mapper.CreateMap<UserCreateDTO, User>();
var user = new user();
Mapper.Map<UserCreateDTO, User>(userdto, user);
Set the debugger to stop after the map call and check to make sure the values were copied in correctly.
精彩评论