質問

I have this:

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

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

I want to get list cars with makes and wheels numbers only:

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();

However, this fails because it produces a sub-query for the wheels and it either has 2 columns (when I add another column for the Wheel) or more than one record (obviously since Wheels is a collection). The "fetch" attribute on the mapping is ignored. Query:

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

Any suggestions? I'd like to keep this in LINQ for abstraction.

役に立ちましたか?

解決

TOP 60 probably won't do what you think it does here

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();

Update: to load exactly 60 root entities and initialize more than one collection

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;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top