ef code first - When exactly does Entity Framework Fire a SQL Command? -
suppose have code like:
public void testwhensqlfires() { var db = new db(); // ef dbcontext var items = db.simpleobjects; // simpleobject implements interface iid var byid = whereid(items, 1); var array = byid.toarray(); } protected ienumerable<iid> whereid(ienumerable<iid> items, int id) { return items.where(i => i.id == id); }
at line in testwhensqlfires() sql run against database?
(this question spun off comments on this answer)
one way find out , test yourself:
open sql server management studio, open new query, select database ef running against , run query:
select top 10 deqs.last_execution_time [time], dest.text [query] sys.dm_exec_query_stats deqs cross apply sys.dm_exec_sql_text(deqs.sql_handle) dest order deqs.last_execution_time desc
this tells past 10 queries have run against database.
set breakpoint on first line of testwhensqlfires(), run code, run above query after stepping on each line. you'll find:
// c# line 1 var db = new db(); --sql line 1 select table_schema schemaname, table_name name information_schema.tables table_type = 'base table' // c# line 2 var items = db.simpleobjects; --sql line 2 select count(*) [sys].[databases] [name]=@1 select [groupby1].[a1] [c1] ( select count(1) [a1] [dbo].[__migrationhistory] [extent1] ) [groupby1] (@1 nvarchar(4000))select top (1) [project1].[c1] [c1], [project1].[migrationid] [migrationid], [project1].[model] [model] ( select [extent1].[migrationid] [migrationid], [extent1].[model] [model], 1 [c1] [dbo].[__migrationhistory] [extent1] ) [project1] order [project1].[migrationid] desc // c# line 3 var byid = whereid(items, 1); --sql line 3 // c# line 4 var array = byid.toarray(); --sql line 4 select [extent1].[id] [id], [extent1].[stuff] [stuff] [dbo].[simpleobject] [extent1]
the final sql query ef fetching data. prior queries warming - verifying database exists, it's using ef5 migration history, , matches current migration history hash.
so answer - 4th line, after .toarray()
called (or call enumerates collection, .tolist(), foreach, etc). notably passing method accepts ienumerable, if there's specific generic involved, not enumerate collection, , not fire off sql earlier necessary.
Comments
Post a Comment