Reputation: 1312
Build ViewModel using two models
Model 1: Person (Id,Name,Address,Phone,CategoryId)
Model 2: Category(CategoryId,CategoryText)
ViewModel: PersonViewModel (Name,Phone, CategoryText)
Question: how would I generate my ViewModel in my controller and forward it to the view:
var model = (from x in db.Person
select new PersonViewModel {
Name = x.Name,
Phone = x.Phone,
CategoryText = ??? }).ToList();
How do I generate CategoryText?
Thanks
Upvotes: 1
Views: 780
Reputation: 30152
You need to join on categories. you may be able to include as the following, if not you just need a join. Try the following (I forget if you can include() in this syntax - somethingin my mind tells me you can't and if that's the case I'll delete this shortly as I see someone just posted the join syntax)
var model = (from x in db.Person.Include(o=>o.Category) //assumes EF 4.1 if not try .Include("Category")
select new PersonViewModel {
Name = x.Name,
Phone = x.Phone,
CategoryText = x.Category.CategoryText }).ToList();
Upvotes: 3
Reputation: 38468
var model = (from x in db.Person
join y from db.Category on x.CategoryId equals y.CategoryID
select new PersonViewModel {
Name = x.Name,
Phone = x.Phone,
CategoryText = y.CategoryText }).ToList();
Upvotes: 1