I have inherited a C# application with EFv4 / .net 4.0.
Analyzing some of the DB calls with the SQL Server Profiler I see some unexpected database calls that come from the application itself (no other users, no other applications or processes are mixed here).
I have a situation where two exact queries get triggered to the database when showing in a WinForm dialog with the queried info. (As it's logic, I would like to avoid the second call... or at least understand from where it comes from).
The first query gets triggered at the form's constructor, where the DataSource gets bind to the DbContext.ClassToShow.
But the second query gets triggered somewhere after this form is shown (ShowDialog()). But I do not know where exactly...
So my question is:
Where should I set the breakpoint in order to stop the application before any query gets triggered by the EntityFramework?
I have tried from the DbContext.ClassToShow property but it stops just the first time.
EDIT:
I have tried changing the way the binding is assigned from:
siteBindingSource.DataSource = mDbContext.Site;
to:
var sites = new List<Site>();
var dbSites = mDbContext.Site;
sites.AddRange(dbSites);
siteBindingSource.DataSource = sites;
Also I have noticed that searching at Visual Studio through the database entity triggers database queries.
Still applies the same question, how can I distinguish between the different places the database is being queried?
It seems that the data binding system can enumerate the data source object multiple times. Each enumeration executes the query again. Entity Framework query objects do not cache their results.
For that reason you must materialize the queries (e.g. using ToList()
).
This is better for reasons of error handling and transaction management as well.