C# Linq或EF-多个连接到具有过滤属性的非匿名对象

C# Linq或EF-多个连接到具有过滤属性的非匿名对象,c#,entity-framework,linq,C#,Entity Framework,Linq,我正在使用EF,不幸的是,includefiltered不是选项。因此,我必须以某种方式重写代码,并从中创建非匿名对象。我决定重写它加入,但它可以是任何有效的 我有实体,简化版汽车。轮胎。制造商。 汽车可以有零到多个轮胎,轮胎可以有零到多个制造商 我想得到特定id的汽车,只有它的轮胎与特定的制造商。 问题是,我的结果是,汽车的轮胎总是有零制造商 我目前的代码是: var car1 = (from c in this.dbContext.Cars

我正在使用EF,不幸的是,includefiltered不是选项。因此,我必须以某种方式重写代码,并从中创建非匿名对象。我决定重写它加入,但它可以是任何有效的

我有实体,简化版汽车。轮胎。制造商。 汽车可以有零到多个轮胎,轮胎可以有零到多个制造商

我想得到特定id的汽车,只有它的轮胎与特定的制造商。 问题是,我的结果是,汽车的轮胎总是有零制造商

我目前的代码是:

 var car1 = (from c in this.dbContext.Cars
                            .Include(cr => cr.Tires)
                            .ThenInclude(crt => crt.Manufacturers)

            join t in this.dbContext.Tires
                            .Include(ct => ct.Manufacturers)
                      on c.ID equals t.CarID into carTires

       from t in carTires.DefaultIfEmpty()
       join m in this.dbContext.Manufacturers on t.ManufacturerID equals m.ID into completeSet

       from cs in completeSet.DefaultIfEmpty()
       where (c.ID == someCarID ) // and later I will add filter for tire's manufacturer


       select new Car
       {
          ID = c.ID,
          Tires = c.Tires
       }
如果我使用代码

       var car2 = this.dbContext.Cars
                .Include(c => c.Tires)
                    .ThenInclude(t => t.Manufacturers)
                Where(c => c.ID == someCarID)
在Car2中有一些制造商

为什么car1轮胎的制造商是空的以及如何修复它

注意:这是中间目标。我的最终目标是获得汽车轮胎只为选定的制造商

试试这个:

var Cars=this.dbContext.Cars.Where(c => c.ID == someCarID).Select(s=> s.Tires).ToList();
现在,您有了这些制造商的轮胎

请尝试:

var manufacturerTires = dbContext.Tires.Where(t => t.ManufacturerID == someManufacturerID);

var carTires = dbContext.Cars.
        Where(car => car.ID == someCarID)
        .Join(manufacturerTires,
              car => car.ID,
              tire => tire.CarID,
              (car, tire) => new { car, tire })
        .ToList();
这将返回一个匿名对象
new{Car,Tire}

如果我们需要获得Car和Car.Tires的现有结构,我们可以在上述查询的末尾添加一个GroupBy,如下所示:

.GroupBy(c => c.car, c => c.tire, (car, tires) => new Car{ ID = car.ID, Tires = tires}); 
//this could be an expensive query as the GroupBy is on all the columns in Car table

如果您要手动加入数据(使用dbcontext),则不必同时指定所有这些include语句?如果没有,您也可以扩展
car2
@jcruz的(工作)方法。实际上,我更喜欢car2方法,但不幸的是,如果没有includefilted(),我不知道如何解决它,因为我无法使用includefilted()。因为真正的问题更复杂,我需要根据所选ID过滤其中一个属性子体,然后从该过滤子体的另一个子属性获取值。谢谢。如果我们更深入,让它更复杂呢?若汽车也有齿轮,齿轮有供应商,供应商有制造商怎么办?我希望对象中的轮胎和齿轮都具有所有子体属性。我明白了,在这种情况下,您可以使用Linq,例如:(从this.dbContext.Cars中的c连接this.dbContext.CarID上的轮胎等于t.CarID在this.dbContext.ManufacturerID上的m等于m.ID,其中c.ID='XXXX'选择c.ToList();谢谢,这是我所需要的!