Mohamad Armoon Mohamad Armoon - 1 year ago 104
C# Question

Entity framework - one to many - select from both table

In my DB I have "Place" and "Image" table. "Image" has a foreign key from Place which means each place can have multiple images.

I select places like this:

var query = (from x in DB.Places
where x.CityId == CityId
select x).ToList();


and when I want to access to its images by:
query.Images.toList();
i get this error :



The ObjectContext instance has been disposed and can no longer be used
for operations that require a connection.





how should be my select query in order to get a place and it's images just by one select query ??

thanks in advance

MA.

Answer Source

You can use eager loading:

var query = (from x in DB.Places
             where x.CityId == CityId 
             select x).Include(p => p.Images).ToList();

Method syntax looks better in that case

var query = DB.Places.Where(p => p.CityId == CityId).Include(p => p.Images).ToList();

Another option - do not dispose DbContext until you get images. E.g. if you are using using statement, just remove it or get images while you are inside using block. But it will use second database query for loading images.

Further reading: Eager Loading and Lazy Loading

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download