Nhibernate - 使用LINQ部分装载行李

时间:2013-05-24 15:44:05

标签: c# linq nhibernate fetch bag

我有这个:

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列(当我为Wheel添加另一列时)或多个记录(显然,因为Wheels是一个集合)。映射上的“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 for abstraction中。

1 个答案:

答案 0 :(得分: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;