Entity Framework DbContext How to Eager Load Records Into Memory

c# eager-loading entity-framework entity-framework-6

Question

Entity Framework 6 is what I'm using.DbContext . To use these entries in the loop, I want to eager load records from the database. I'd like to use an example to explain (please don't tell me that it's impractical in the actual world; it's just an example).

I possessDataGridView showing a list of students. In theStudent table with a column for each entryfavorite_subject_id .

displaying each student's academic record inDataGridView I'm trying to locate and show the subject name from theSubject table containing the pupils'favorite_subject_id (Assume there is no database connection between them. I am aware that it belongs in a real-world project. But I'm simply using that as an example to make my point.)

I initially created this idea as the following code:

foreach (DataGridViewRow row in gridView.Rows)  
{    
    if (!row.IsNewRow)    
    {      
        var student = (Student)(row.DataBoundItem);
        var favorite_subject = dbContext.Subjects.find(student.favorite_subject_id);
        row.Cells[colFs.Index].Value = favorite_subject.subject_name.ToString();
    }  
}

However, this code's implementation will affect every student's record in the database. It will undermine the effectiveness.

Therefore, before looping, I want to eagerly load the subject records into memory. I just want to search these eagerly loaded data from the RAM during the loop. The issue is that I'm not sure how to eagerly load the records into memory in the appropriate (or optimal) way.

For this, I created some software. But I'm not sure if that is the best course of action.

var lstSubjects = dbContext.Subjects.ToList<Subject>();

foreach (DataGridViewRow row in gridView.Rows)  
{    
    if (!row.IsNewRow)    
    {      
        var student = (Student)(row.DataBoundItem);
        var favorite_subject= lstSubjects .Find(x => x.subject_id == student.favorite_subject_id);
        row.Cells[colFs.Index].Value = favorite_subject.subject_name.ToString();
    }  
}

The question then becomes: How can the records from the database be eagerly loaded into the memory (by utilizingDbContext )?

1
3
11/1/2014 1:09:24 PM

Accepted Answer

ZZZ_tmp
1
11/1/2014 12:39:20 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow