Reputation: 571
I am trying to understand how to fill a viewmodel with only a few properties from two different models. I know how to limit display in a view by including all columns (i.e. use an include to join the two models and only display the fields I need to). But I want to learn how to do this in a ViewModel so my views are fields to display for a specific view.
Suppose I have two models (let's assume a one-to-one relationship):
public class Person
{
public int PersonId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
}
public class Address
{
public int AddressId { get; set; }
public int PersonId { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
Let's say in the View I just want LastName, FirstName and City (from Address). So I coded my ViewModel like this:
public class PersonCityViewModel
{
public int AddressId { get; set; }
public int PersonId { get; set; }
public string City { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
}
In my View I want to show a list of people with names and cities.
I have a PersonCityController, in which I did this:
public ActionResult Index()
{
PersonCityViewModel vm = new PersonCityViewModel();
vm.____ = db.????
//how do I proceed?
}
Thanks!
Upvotes: 0
Views: 283
Reputation: 19161
You are almost there, just pull back your Person
and Address
instances that are related, then do:
PersonCityViewModel vm = new PersonCityViewModel() {
AddressId = address.AddressId,
PersonId = person.PersonId,
... etc.
}
The next bit depends entirely on your data structure (e.g. one address per user, maybe it is linked and stored in the Address field of the user), but you might do this with a LinqToSql query, with the psuedocode similar to:
var personQuery = (from p in myDbContext.Persons
from a in myDbContext.Addresses
where p.PersonId == a.PersonId
select new {
Person = p,
Address = a
};
// you should use FirstOrDefault here and check for nulls, really ...
var result = personQuery.First(r => r.Person.PersonId == personId);
PersonCityViewModel vm = new PersonCityViewModel() {
AddressId = result.Address.AddressId,
PersonId = result.Person.PersonId,
... etc.
}
If you are doing a lot of mapping, consider using an automatic object mapper to help you out, such as AutoMapper
Upvotes: 2