1

I've mapped my classes with default EF way, and all my FKs are EntityCollection, so for example Bike.Wheels would be EntityCollection.

How do I work with Wheels?

  • I want to retrieve 1st and 2nd wheel
  • I want to loop through Wheels
  • I want to get all wheel.Bolts

I could not use get/select/[].

Am I missing something?

yoozer8
  • 7,361
  • 7
  • 58
  • 93
Massive Boisson
  • 1,617
  • 7
  • 22
  • 28

1 Answers1

3

Well, some operations are really simple - others are a bit kludgy - so you might want to redesign some of your approaches to use the easy methods.

To loop over all your wheels, just use a foreach statement:

using(BikeEntities ctx = new BikeEntities())
{
   // assuming you just somehow pick a bike to inspect the wheels for
   Bike myBike = ctx.Bikes.FirstOrDefault(b => b.BikeID == 5);

   foreach(Wheel w in myBike.Wheels)
   {
       // do something with your wheel  
       foreach(Bolt b in w.Bolts)
       {
           // do something to al the bolts on your wheel
       }           
   }
}

Getting the first, second etc. of a collection is a bit more tricky, since you cannot use the usual array indexing. You can:

  • use the .Skip() method - but that's a bit clumsy for single object retrieval
  • if the collection isn't too big, you could "materialize" it into a List<T> and then use array indexing

So either you use something like this:

Wheel firstWheel = myBike.Wheels.FirstOrDefault();
Wheel secondWheel = myBike.Wheels.Skip(1).FirstOrDefault();

or you materialize the collection into a list:

List<Wheel> myWheels = myBike.Wheels.ToList();

Wheel firstWheel = myWheels[0];
Wheel secondWheel = myWheels[1];
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Yes, that helps a lot but... Isn't there a way to do a join for bolts so that materialized version contains the bolts already selected from the db. – Massive Boisson Aug 15 '10 at 09:48
  • @Massive Boisson: I don't know exactly what you mean... can you elaborate? A "join for bolts" ? Join with what? – marc_s Aug 16 '10 at 04:38
  • @Massive Boisson: If the bike object is in the database, then you can use the `CreateSourceQuery()` method on the `Wheels` property, and then call `Include("Bolts")` on the resulting `ObjectQuery` object. – Jean Hominal Jun 21 '11 at 07:40