views:

30

answers:

2

I am using Entity Framework for my .NET application. I have been able to return objects and their directly-related objects as well (very convenient), but I am having trouble getting the objects of those objects.

 IEnumerable<Lot> i = (((ObjectSet<Car>)_carRepository.GetQuery())
                                    .Include(a => a.CarTypes).Take(10).ToList()

This works and I can access carTypes, however I cannot figure out how to access tables associated with CarTypes (e.g. tables which have fields associated with the car types).

I tried to use a Join however I was unable to figure out how to get it to work right.

All help appreciated.

A: 

I believe you can chain Includes... So you could have something like

.Include(a => a.CarTypes.Company) 

If you're just using one or two fields from each type, one possibility might be to create a view in the DB. Then you could add this view to your EF model and access those properties directly.

taylonr
That does not work unfortunately. Are you sure that is normally possible? If so this may be a serious issue with our underlying architecture.
smdrager
I'm not positive. I haven't needed to do multiple includes, but I thought I had read that somewhere you could have 2 or 3 or n include statements
taylonr
A: 

Include can be chained, but you have to keep in mind that it uses strings rather than lambdas. So you do .Include("CarTypes.Company") if you want a two level include. You can also chain Include statements which means including more than one branch from the same top level--eg. .Include("CarTypes").Include("SomeOtherTypeFromTheSameParentAsCar").

You should keep in mind, though, that deep Include statements may not produce the best possible performance because every part of an Include just adds on to the one query that you are building so you will get a larger and more complex query which does a whole bunch of joins under the covers. Sometimes it's more effective to do a few Includes in one query and then issue a second query to get the rest of your data or something like that.

With EF4 you can also setup lazy loading which can sometimes make this kind of thing even easier (but of course it produces multiple roundtrips rather than one or two very large roundtrips).