Skip to content

Instantly share code, notes, and snippets.

@troygoode
Created November 11, 2010 20:01
Show Gist options
  • Save troygoode/673079 to your computer and use it in GitHub Desktop.
Save troygoode/673079 to your computer and use it in GitHub Desktop.
public ActionResult UpdateProfile(ProfileInputModel input, Individual individual){
if(!ModelState.IsValid)
return View(new ProfileInputModel());
Mapper.Map<ProfileInputModel, Individual>(input, individual);
foreach(var email in input.Emails)
individual.UpdateEmailAddress(email.Key, email.Value);
return RedirectToAction("ViewProfile");
}
public class ProfileInputModelMapping : IAutoMapping{
public void CreateMappings(){
Mapper.CreateMap<ProfileInputModel, Individual>()
.ForMember(dest=> dest.SocialSecurityNumber, opt=> opt.MapFrom(src=> src.Ssn))
.ForMember(dest=> dest.DateOfBirth, opt=> opt.MapFrom(src=> src.Dob))
.ForMember(dest=> dest.Emails, opt=> opt.Ignore());
}
}
public class ProfileInputModel{
[Required, EachValueIsAnEmailAddress]
public Dictionary<string,string> Emails{ get; set; }
public string Ssn{ get; set; }
public DateTime Dob{ get; set; }
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
public class Individual{
public Individual(){
_emails = new List<EmailAddress>();
}
private ICollection<EmailAddress> _emails;
public IEnumerable<EmailAddress> Emails{ get; private set; }
public string SocialSecurityNumber { get; set; }
public DateTime DateOfBirth { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public void UpdateEmailAddress(string type, string address){
var email = _emails.SingleOrDefault(e=> e.Type == type);
if(email == null)
_emails.Add(new EmailAddress(type, address));
else
email.UpdateAddress(address);
}
}
public class EmailAddress{
public EmailAddress(string type, string address){
Type = type;
Address = address;
}
public string Type{ get; private set; }
public string Address { get; private set; }
public void UpdateAddress(string address){
Address = address;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment