Linq behind the scenes
I would very much appreciate a detailed explanation of (and if) there's a difference in what's going on behind the scenes of the following Linq to Entities related code snippet given these scenarios:
A. The "foreach" loop was within the "using" clause B. Instead of Linq to En开发者_C百科tites i was using a silimilar mapping running the query on Linq to Sql. C. A+B.the code:
ILookup<string, tblProduct> productBooks;
using (TbsDBEntities tbsDbEntities = new TbsDBEntities())
{
productBooks = (from tbsDbEntity in tbsDbEntities.tblProducts
orderby tbsDbEntity.Title
select tbsDbEntity).ToLookup(p => p.Title.Substring(0, 1).ToUpper());
}
foreach (IGrouping<string, tblProduct> productBook in productBooks)
{
if (productBook.Key[0] >= 'A' && productBook.Key[0] <= 'Z')
{
HtmlAnchor anchor = new HtmlAnchor();
anchor.InnerText = productBook.Key+" ";
anchor.HRef ="/"+ productBook.Key;
divHeader.Controls.Add(anchor);
}
I looked at this carefully and thought "that won't work" after the using
is closed.
However the ToLookup()
actually does the execution of the SQL statement, so that's all good. Leaving it as IEnumerable will cause it to fail in your second foreach as the context will have been disposed. Linq to SQL will be fine with this code.
Behind the scenes: The code is accessing the database list of products through the entities mapping.. typically one would have written this code for ADO.NET Entity framework + Linq to entities.
The code uses linq to extract rows of data instead of using typical sql queries like "select * from products".. the entities mapping is expected to generate a query behind the scenes and get data.. if you have sql profiler like tool you will be able to see the query that the code passes to sql server.
The foreach is typically creating links, for each product returned from the linq statements... and its adding the links inside a .. An if statement is probably protecting the code from product names which dont start with an alphabetical character.. and so probably the check for >= A and <= Z
A. Shouldn't have a difference.
B. You might have a considerate performance gain if tblProducts has a lot of data.. because linq-to-database would help avoid the construction of entity objects for all the data.
C. Same as B... because I believe having the for loop inside 'using' doesn't make it any different
精彩评论