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.

Answers


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.


Need Your Help

Can't access json data

javascript html json

I know this is a simple question, but I can't access the data in my json object. It looks like this:

Div height not expanding to all elements

html css

I have a div that i use as a simple modal popup. The height of this div is set to auto, however when I view it it doesn't expand all the way down to cover all the elements inside of it. Any idea ...