2015-08-28 70 views
3

我有一個數據庫中沒有任何定義的關係的兩個表。實體框架ViewModel

public class Person 
    { 
     public int PersonID { get; set; } 
     public string Name { get; set; } 
    } 

    public class Car 
    { 
     public int CarID { get; set; } 
     public string Model { get; set; } 
     public int PersonID { get; set; } 
    } 

我創建了一個PersonViewModel如下

 public class PersonViewModel 
    { 
     public int PersonID { get; set; } 
     public string Name { get; set; } 

     public virtual ICollection<Car> Cars { get; set; } 
    } 

我想做些事情的下方,但很明顯這是不正確。 任何幫助將不勝感激。謝謝

public PersonViewModel GetPerson(int personID) 
    { 
     var query = from p in db.Car 
        join c in db.Car on p.PersonID equals c.PersonID 
        where p.PersonID == personID 
        select new PersonViewModel() 
        { 
         PersonID = p.PersonID, 
         Name = p.Name 
         Cars = new List<Car>() 
         { 
          CarID = c.CarID, 
          Model = c.Model, 
          PersonID = p.PersonID 
         } 
        }; 

     var person = query.FirstOrDefault(); 

     return person; 
    } 
+4

嘗試將其更改爲p在db.Person –

回答

1

你必須加入PersonCar表,然後使用這個連接組生成的列表Cars

var query = from p in db.Person 
       join c in db.Car on p.PersonID equals c.PersonID into personCars 
       where p.PersonID == personID 
       select new PersonViewModel() 
       { 
        PersonID = p.PersonID, 
        Name = p.Name 
        Cars = personCars.ToList() 
       }; 

    var person = query.FirstOrDefault(); 
+0

正是醫生的命令。謝謝! –

0

你正在做同樣的表之間的連接發生變化的第一個表:

from p in db.Person