0

i have a DataContext called dtContext which has many entities. now my data in database is huge, so i was wondering if i create a new DataContext will all the data from my database fetched into entities? meaning all the entities filled with data from my database as soon as newing is done? or is it fetches the data only when you call an entity from LINQ query? for example:

line 1: dtContext dt = new dtContext();
line 2: IEnumerable<MyEntity> query = from q in dt.MyEntities select q;

on which line MyEntities will represent the actual data from database?

jim
  • 494
  • 2
  • 5
  • 23

4 Answers4

1

It doesn't query your database until you enumerate over the query or call ToList(), ToArray(), etc. This is called Deferred Execution.

Many of the Standard Query Operators return elements when iterated over using the foreach statement. These operators essentially do no work UNTIL the first element is requested, and then suspend until the next element is requested. Until the returned query is iterated over, no work is carried out internally for any of these statements. This deferred execution allows you to control when and if potentially lengthy work is carried out.

If you want a query to be realized immediately, call ToList, ToArray or any of the other operators that need to enumerate the entire sequence to return a result.

LINQ leverages a language feature added in C# 2.0 that made it simpler when writing methods that returned one element at a time when iterated over. The yield return statement essentially suspends a loop by returning a value, picking up exactly where it left off next time a MoveNext is called.

The MSDN library describes operators that use Deferred Execution as:

This method is implemented using deferred execution. The immediate return value is an object that stores all the information required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

jrummell
  • 42,637
  • 17
  • 112
  • 171
1

The answer in none. the first row won't get any data since you didn't write a query. The second line won't get any data either since you just wrote the query but didn't executed it. Executing a query can be done when iterating over the result (like foreach, ToArray(), First() etc)

Amiram Korach
  • 13,056
  • 3
  • 28
  • 30
1

You're referring to features called eager loading and lazy loading, you might find this useful, and also this.

Community
  • 1
  • 1
Paul Aldred-Bann
  • 5,840
  • 4
  • 36
  • 55
0

The point at which you try to iterate over the result set of your query.

If you want to pull back a subset of the data then add a where clause to your query.

devdigital
  • 34,151
  • 9
  • 98
  • 120