查询多对多Linq Join

本文关键字:Join Linq 查询 | 更新日期: 2023-09-27 18:07:17

我使用Linq-SQL实体为我的MVC2应用程序。

我有那些表/实体

Person (ID, Name,姓)汽车(ID,型号,名称)经销商(ID, Name)

我有那两个多对多表

Persons_Cars (ID, ID_Person, ID_CAR)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辆车,我收到同一个人两次,有2辆车的列表。

例子布朗先生有两辆汽车还我收到布朗先生-->汽车清单(Car1, Car2)Mr Brown ->汽车(Car1, Car2)列表

所以我需要,如果一个人有2辆车,我只得到一个结果,他有自己的车

是否有更好的方法来编写这个查询?怎样才能解决我的问题?

谢谢

查询多对多Linq Join

我认为简单的子查询就可以完成这项工作(对于经销商也是如此):

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将为您做join):

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

有了Person和Car的正确属性和数据库关系,就可以在上下文的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

或者返回Person及其填充的Car列表:

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