I’ve got the following models:
public abstract class PersonBase : EntityWithTypedId
{
public PersonBase()
{
this.ProfileImages = new List<ProfileImage>();
}
public string name;
[Required]
public string Name
{
get { return name; }
set
{
name = value;
this.UrlFriendlyName = value.ToUrlFriendly();
}
}
public string UrlFriendlyName { get; protected set; }
[UIHint("UploadImage")]
public List<ProfileImage> ProfileImages { get; set; }
}
public class ProfileImage
{
public int PersonId { get; set; }
public byte[] Image { get; set; }
}
And my viewmodel:
public class PersonDetailsViewModel
{
public string Name { get; set; }
public IEnumerable<HttpPostedFilebase> ProfileImages { get; set; }
}
Now my question is, how can I map those with automapper? I mean the ProfileImage also needs the PersonId (which could be inserted by the Entity Framework on insert). Do I need to change the naming in the ViewModel or?
I’m going to presume that personId is part of your edit route values.
on startup somewhere
If your Person/Profile Image relationship is setup correctly in EF and you have change tracking turned on (should be on by default) EF should automatically figure out the PersonId for the image.
For an insert it should also just work, with EF doing the heavy lifting around the personId, you may need to create the person entity yourself and add it to the context first, but not neccesarily.
It gets a bit trickier when trying to update/delete existing profile images rather than just adding to them each time, I have another stackoverflow answer goes into that in more detail – When using DTOs, Automapper & Nhibernate reflecting changes in child collections of DTO in domain object being updated