Scottie
Scottie

Reputation: 11308

EF4 Lazy Loading - How do I force a load?

I have the following code:

    public IEnumerable<RMAInfo> GetAllRMAsByReseller(string resellerID)
    {
        using (RMAEntities context = new RMAEntities())
        {

            IEnumerable<RMAInfo> ret = from r in GetRMAInfos_Internal(context)
                                       where r.ResellerID.ToUpper().Trim() == resellerID
                                       select r;

            return ret;
        }
    }

When I try and access the return value, I get the expected error of:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection. 

I know this is happening because of lazy loading, and it's trying to load now that the context has been closed (via the using going out of scope).

My question is how do I force a load before I exit the method?

I originally did it like

return ret.ToList<RMAInfo>();

This worked fine, but I'm not sure if it's the correct or best way to do it?

Upvotes: 2

Views: 1094

Answers (2)

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

query.ToList(); is the correct way to force load the results. How else would you force evaluation of linq query?

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190945

That is perfectly fine and accepted.

Upvotes: 1

Related Questions