简体   繁体   中英

C# Entity Framework Lazy Loading Isn't Loading

I've done all the readings I can find on Entity and lazy loading, as well as other questions here, but for the life of me I can't get this working. Here's my SQL for the DB:

CREATE TABLE corporations(
corporationID bigint PRIMARY KEY
);

CREATE TABLE Character(
personID bigint PRIMARY KEY,
corporationID int NOT NULL,
FOREIGN KEY (corporationID) REFERENCES corporations(corporationID)
);

And the Entity code to get it ( * EDITED from original, still broken * ):

DBEntities context = new DBEntities();
public Character Character_GetByID(long CharacterID)
        {
            context.ContextOptions.LazyLoadingEnabled = true;
            Character character = context.Characters.Where(c => c.CharacterID == CharacterID).FirstOrDefault();      
            return character;
        }

So from my understanding, with this I should be able to go

Character char = Character_GetByID(characterID);
Corporation corp = char.Corporation;

The "char.Corporation" object exists, Entity created it properly from the foreign key. But when I run the above code, "corp" always returns as NULL (even though I know for sure that the relevant corporation is in the DB).

One thing I did notice is that in the auto-generated Entity Character object, it has the function:

public virtual Corporation Corporation
        {
            get { return _corporation; }
            set
            {
                if (!ReferenceEquals(_corporation, value))
                {
                    var previousValue = _corporation;
                    _corporation = value;
                    FixupCorporation(previousValue);
                }
            }
        }

Which seems odd, because I would assume that with lazy loading the "get" function would be something like "if null, try to get Corporation from database". Any thoughts would be highly appreciated.

* EDIT * Request for how lazy loading is configured:

In my Context class, for every constructor I have

this.ContextOptions.LazyLoadingEnabled = true;

And as you can see from the first C# function up above, I tried setting it as true in the function itself, just before querying it.

Lazy loading is a functional provided by object context (DBEntities class instance in your case). So, it will work only when entity object is attached to some DBEntities instance. When Character_GetByID method is done, context is disposed, entity is detached, and your lazy loading request cannot be performed.

Remove the using statement, as when you use this dbcontext is disposed right away

using (var context = new DBEntities())
{
   ...
}//context is disposed here... lazy loading is not possible

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