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

▼魔方 西西 提交于 2019-12-04 05:48:51

问题


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();


来源:https://stackoverflow.com/questions/49292737/entity-framework-6-disable-lazy-loading-and-specifically-load-included-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!