1

How can I know which of the following linq queries will be executed?

    // I think this will not be executed
    var temp1 = PdvEntities.Entities.Products;

    // Not sure
    IEnumerable<Data.Products> temp2 = PdvEntities.Entities.Products;

    // will not be executed
    var temp3 = from a in PdvEntities.Entities.Products select a;

    ListView lv1 = new ListView();
    lv1.DataContext = temp1; // will this make the first query to be executed?
    lv1.ItemsSource = temp2; // will this make the second query execute?

    // I think this will be executed
    var temp4 = PdvEntities.Entities.Products.ToList();

note I am using the ADO.Net entity data model to execute the queries from the table Products in my database

Tono Nam
  • 34,064
  • 78
  • 298
  • 470

3 Answers3

2

The concept is called "Deferred Execution" and the general rule of thumb is that the query won't be executed until you actually access the underlying data. Another way to think about it is that when you're no longer returning IEnumerable or IQueryable, you're probably executing code, like your last temp4 is putting in a List<T> which is definitely accessing the data.

Here's a decent explanation:

http://www.codeguru.com/columns/vb/article.php/c16935

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Brad Rem
  • 6,036
  • 2
  • 25
  • 50
1

temp2 will be evaluated when the UI updates the listview.

temp1 will never be evaluated unless you have a binding to the ListView's DataContext.

Terkel
  • 1,575
  • 8
  • 9
1

For the DataContext, it really depends on what you do with it. If you never enumerate the collection, the query will never be executed. For an ItemsSource, I believe it will enumerate it when you assign it in order to create the necessary objects in your listview, as long as it is showing to the user. If it is not showing, I don't think the query will be executed. The easy way to tell is to mock up something real quick that does what you put in your code sample then step through in Visual Studio. That way you can check in your locals window afterward to see if the collection has been filled in or not.

Scott M.
  • 7,313
  • 30
  • 39