-2

How can i get a list with all the data and reference data from database from a static function? I try to use db.Configuration.LazyLoadingEnabled = true; but the function return only the project info and the reference data was null.

public static Project GetProject(Guid ProjectID)
        {
            if (!ProjectID.Equals(null))
            {
                using (var db = new dbEntity())
                {
                    return db.Projects.Single(Project => Project.Id.Equals(ProjectID));

                }

            }
            return null;
        }

Error:

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

Where i call the function:

@{var project = StaticMethods.GetProject(Guid.Parse(ViewContext.RouteData.Values["id"].ToString()));}
@for(var item in project.Users().ToList()){
 ....
}
Cristian
  • 37
  • 1
  • 8
  • What is the structure of `Project` – TheGeneral Apr 08 '19 at 08:42
  • @MichaelRandall its a auto-generated model from db ``` public System.Guid Id { get; set; } public string Name { get; set; } public string Number { get; set; } public virtual ICollection Users { get; set; } ``` – Cristian Apr 08 '19 at 08:50
  • Also, `if (ProjectID.Equals(null))` is going to throw a NullReferenceException if `ProjectID` is `null`. – CodeCaster Apr 08 '19 at 08:56

2 Answers2

0

You can use Linq eager loading and express explicitly what do you want to include to resulting objectgraph. Eager loading is achieved with .Include()-method.

You did not provide model classes of your entities, but I assume that relationship is one-one (Project has Reference as property). Following snippet loads Project with it's Reference-property:

public static Project GetProject(Guid ProjectID)
{
    if (!ProjectID.Equals(null))
    {
        using (var db = new dbEntity())
        {
            return db.Projects.Include(r => r.Reference).Single(Project => Project.Id.Equals(ProjectID));
        }
    }
    return null;
}
Risto M
  • 2,919
  • 1
  • 14
  • 27
0

In short, lazy loading is the problem.

It's caused by the following:

  1. You open the DbContext
  2. Perform your query
  3. Return your Project
  4. Access a virtual property which is trying to lazily load a related resources after the DbContext is disposed.

You will have to do one of the following:

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141