简体   繁体   中英

Entity Framework - lazy loading failing but eager loading fine - how to fix/debug?

I am using entity framework 4.3.1 against a sql server 2012 database and I have a database with these tables (there are more but the relevant bits are below):

Customer

    CustomerNumber nvarchar(10) not null primary key

SalesDocument

    SalesDocumentNumber nvarchar(10) not null primary key
    CustomerNumber nvarchar(10) not null

I am running the following snippet of code:

const string docNumber = "111348718";
IQueryable<SalesDocument> docs = factory.CreateSalesDocumentRepository().All;

var ssd = docs.Single(s => s.SalesDocumentNumber.Equals(docNumber));

if (ssd.Customer == null)
    Console.WriteLine("NOOOOOOO");

ssd = docs
    .Include(s => s.Customer)
    .Single(s => s.SalesDocumentNumber.Equals(docNumber));

if (ssd.Customer == null)
    Console.WriteLine("YESSSSSS");

and I get only NOOOOOOO printed.

So it seems that the lazy loading is not working but eager loading is.

What gives and how on earth can I debug what has gone wrong in this scenario (what are likely causes for this to fail - it feels like a bug in EF to me but I am holding off on declaring that and throwing the whole steaming pile out of the window)? Surely the configuration is OK if the second one is working fine...?

I don't mean to teach you to suck eggs, but have you enabled LazyLoading in your ObjectContext ?

ie: in the ObjectContext constructor

 this.ContextOptions.LazyLoadingEnabled = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM