Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 804
M.Armoun Avatar asked Jun 10 '26 08:06

M.Armoun


2 Answers

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

like image 59
Sergey Berezovskiy Avatar answered Jun 11 '26 21:06

Sergey Berezovskiy


There are 2 options:

1) Enable eager load (not good idea)

2) Keep Lazy loading and Include entity you want to get.

Option 2:

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

The exception you are getting is because of LazyLoading enabled on context object. You are trying to access the property outside EF i guess, when it's already disposed.

In Lazy Loading call to the property for the first time is actually connecting DB and retrieving data you need.

For more information please follow that link: https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

like image 26
madoxdev Avatar answered Jun 11 '26 22:06

madoxdev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!