0

我有这个:

class Car:Entity { string Make { ... } ICollection<Wheel> Wheels { ... } 
  ... tons of props ... }

class Wheel:Entity { Car Car { ... } int Number { ... } int Size { ... } 
  ... tons of props ... }

我只想获取带有品牌和车轮编号的汽车清单:

var data =
  this.Repository.Data
    .Select(x => new Allocation
    {
      Make = x.Make,
      Wheels =
        x.Wheels
          .Select(a =>
            new Wheel
            {
              Number = a.Number,
              Size = a.Size,
            })
          .ToArray(),
    })
    .Take(60)
    .ToArray();

但是,这失败了,因为它为轮子生成了一个子查询,并且它有 2 列(当我为轮子添加另一列时)或多个记录(显然因为轮子是一个集合)。映射上的“fetch”属性被忽略。查询

exec sp_executesql N'
select TOP (@p0)  
        car0_.Make as col_0_0_, 
        (select 
                wheel1_.Number, 
                wheel1_.Size 
            from dbo.Wheels wheel1_ 
            where car0_.Id=wheel1_.CarId) as col_1_0_ 
    from dbo.Cars car0_ 
',N'@p0 int',@p0=60

有什么建议么?我想将其保留在 LINQ 中以进行抽象。

4

1 回答 1

1

TOP 60 可能不会做你认为它在这里做的事情

var query = from car in Repository.Data
            from wheel in car.Wheels
            select new { car.Id, car.Make, wheel.Number, wheel.Size };

var data = query
    .Take(60)
    .GroupBy(a => a.Id, (key, values) => new Allocation
    {
      Make = values.First().Make,
      Wheels = values.Select(a => new Wheel
          {
              Number = a.Number,
              Size = a.Size,
          })
          .ToArray(),
    })
    .ToArray();

更新:准确加载 60 个根实体并初始化多个集合

var cardata = Repository.Data.Select(car => new { car.Id, car.Make }).Take(60).ToList();

foreach(var c in cardata)
{
    var carId = c.Id;
    a.Wheels = aRepository.Data.Where(c => c.Id == carId).SelectMany(car => car.Wheels).Select(w => new Wheel { Number = w.Number, Size = w.Size}).ToFuture();

    a.Foos = aRepository.Data.Where(c => c.Id == carId).SelectMany(car => car.Foos).Select(f => new Foo { Bar = f.Bar }).ToFuture();
}

cardata[0].Wheels.Any();  // execute the futures
return cardata;
于 2013-05-28T13:33:46.033 回答