Having just figured out how to populate my ViewModel from a model using Automapper, I am now onto the next challenge – populating the ViewModel properties from a joined table.
The image below depicts my simple database.
My ViewModel class is defined as:
public class PersonViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Nullable<int> Age { get; set; }
public Nullable<int> SuffixId { get; set; }
public string PersonStatus { get; set; }
public string PersonPreference { get; set; }
public virtual Suffix Suffix { get; set; }
} enter code here
Note the additional fields of PersonStatus and PersonPreference that will come from joining PersonInfo to Person. Here is the code I use to instantiate my mapping configuration:
Mapper.CreateMap<PersonViewModel, Person>();
Mapper.CreateMap<Person, PersonViewModel>();
And now the code to populate the ViewModel
List<PersonViewModel> persons = null;
using (var context = new DemoEntities())
{
persons = (from p in context.People.AsEnumerable()
join i in context.PersonInfoes on p.Id equals i.PersonId
select Mapper.Map<PersonViewModel>(p)).ToList();
return persons;
}
How would I populate the two joined properties (PersonStatus and PersonPreference) from this setup?
Thanks in advance!