2013-04-03 74 views
3

我使用LINQ-SQL實體爲我的MVC2應用。查詢的LINQ加入多對多

我有這些表/實體

人(ID,姓名,姓) 汽車(ID,型號,名稱) 經銷商(ID,姓名)

,我有那些2多對多表

Persons_Cars(ID,ID_Person,ID_CAR)Persons_Resellers(ID, ID_Person,ID_Reseller)

public MyModel { 

    //Some Fields 

    public List<CarPerson> carList; 

    public CarPerson 
    { 
     String detail; 
     int id; 
    } 
} 
var query=(from person in data.Person 

        join PerCar in data.Persons_Cars on person.ID equals Persons_Cars.ID_Person into JoinedPerCar 
        from PerCar in JoinedPerCar.DefaultIfEmpty() 

        join car in data.car on PerCar .id_car equals car.ID into JoinedCarPe 
rson 
        from car in JoinedCarPerson.DefaultIfEmpty() 

        join PerReseller in data.Persons_Resellers on person.ID equals PerReseller .id_person into JoinedPersReseller 
        from PerReseller in JoinedPersReseller.DefaultIfEmpty() 

        join Reseller in data.Reseller on PerReseller.id_reseller equals Reseller.ID into JoinedResellerPers 
        from Resller in JoinedFormazioneComp.DefaultIfEmpty() 

        where person.ID_USER == USER.ID 
        select new MyModel 
           { 
            carList = JoinedPerCar.Select(m=>new CarPerson {detail=m.car.Model,id = m.ID}).ToList()}, 
           //Other 
           }); 

我知道,這是完全錯誤的,但我是新進的LINQ SQL 我現在有一個問題:

查詢工作,但我的結果是錯誤的。事實上,如果一個人有兩輛汽車,我將兩輛同一輛車與兩輛汽車列表一起收回。

布朗具有2汽車 我Recive 布朗--->車的列表(分享幫助,CAR2) 布朗--->車的列表(分享幫助,CAR2)

所以我需要,如果一個人有2輛車我只得到1的人結果與他自己的汽車

有沒有寫這個查詢更好的方法嗎? 如何解決我的問題?

感謝

回答

8

我想簡單的子查詢會做的工作(同樣爲經銷商):

from p in data.Person 
select new MyModel { 
    carList = (from pc in data.Persons_Cars 
      join c in data.car on pc.id_car equals c.ID 
      where pc.ID_Person == p.ID 
      select c).ToList() 
}; 

如果您已經定義了導航屬性,那麼查詢會更簡單(LINQ將不參加對你):

from p in data.Person 
select new MyModel { 
    carList = p.Person_Cars.Select(pc => pc.Car).ToList() 
}; 
2

隨着對人與車和數據庫關係的權利屬性,這可以在你的環境的OnModelCreating方法設置,這樣你就不需要一個Person_Cars模型在上下文:

modelBuilder.Entity<Car>() 
       .HasMany(x => x.People) 
       .WithMany(y => y.Cars) 
       .Map(z => 
       { 
        z.MapLeftKey("CarID"); 
        z.MapRightKey("PersonID"); 
        z.ToTable("Person_Cars"); 
       }); 

那麼你應該能夠通過讓你的人的汽車:

from p in context.People 
where p.PersonID = pID 
select p.Cars 

或與人口租車返回列表中的人:

context.People.Where(p => p.PersonID == pID).Include(c => c.Cars).FirstOrDefault();