Entity Framework 6: Disable Lazy Loading and speci

2020-05-08 07:23发布

问题:

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)
                .Include(d=>d.Note)
                .Include(d=>d.Note.User);
            return result.ToList();

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

回答1:

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
    }).ToList();