Entity Framework 6: Disable Lazy Loading and specifically load included tables

entity-framework entity-framework-6 lazy-loading


Our current system is using Lazyloading by default (it is something I am going to be disabling but it can't be done right now)

For this basic query I want to return two tables, CustomerNote and Note.

This is my query

            using (var newContext = new Entities(true))
                newContext.Configuration.LazyLoadingEnabled = false;

                var result = from customerNotes in newContext.CustomerNotes.Include(d=>d.Note)
                             join note in newContext.Notes
                                on customerNotes.NoteId equals note.Id
                             where customerNotes.CustomerId == customerId
                             select customerNotes;

                return result.ToList();

My result however only contains the data in the CustomerNote table

The linked entities Customer and Note are both null, what am I doing wrong here?

I got it working with the following which is much simpler than what I've found elsewhere

            Context.Configuration.LazyLoadingEnabled = false;
            var result = Context.CustomerNotes.Where<CustomerNote>(d => d.CustomerId == customerId)
            return result.ToList();

This returns my CustomerNote table, related Notes and related Users from the Notes.

3/15/2018 7:05:00 AM

Accepted Answer

That is callled eager loading you want to achieve.

var customerNotes = newContext.CustomerNotes.Include(t=> t.Node).ToList();

This should work, i don't really understand the keyword syntax. If the code above doesn't work try this:

        var customerNotes = newContext.CustomerNotes.Include(t=> t.Node).Select(t=> new {
        Node = t.Node,
        Item = t
3/15/2018 7:00:17 AM

Related Questions


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