Question

I am using Service Stack as my system's API and I'm using Entity Framework to get data from my SQL Server DataBase. Although, I cannot retrieve any data from a list of objects generated by entity framework.

[Route("/getInterventions","GET")]
public class GetInterventions
{

}

public class GetInterventionsResponse
{
    public List<Intervention> interventions { get; set; }
    public ResponseStatus ResponseStatus { get; set; }
}

public class GetInterventionsService : Service
{
    public object Any(GetInterventions request)
    {
        using (var dbConnection = new operationsContext())
        {
            List<Intervention> dbItems = dbConnection.Interventions.ToList();

            return new GetInterventionsResponse{
                interventions = dbItems
            };
        }
    }
}

From the client side I get:

The ObjectContext instance has been disposed and can no longer be used for "operations"(name of db) that require a connection.

So with this error I can verify that the problem as to do with the list that acts like a "virtual" list, and its objects are not returned to the client side, but are passed as a reference or something like that. So how can I deep copy this list and retrieve a clone of it?

Thanks anyways

Was it helpful?

Solution

It looks like the list is no longer accessible when the context gets disposed, possibly because the variable was defined within the scope of the context. Try defining dbItems outside of the using statement:

public object Any(GetInterventions request)
{
    List<Intervention> dbItems;

    using (var dbConnection = new operationsContext())
    {
        dbItems = dbConnection.Interventions.ToList();
    }

    return new GetInterventionsResponse{
        interventions = dbItems
    };
}

Also, you may run into this issue if you are expecting navigation properties of Interventions to be loaded, which they will not be with your code because EF uses lazy loading. For example, if Intervention has a Person navigation property, you would need to include that to have it be available. Like this:

dbItems = dbConnection.Interventions.Include(x => x.Persons).ToList();

Edit based on comment below:

You can also have includes multiple levels deep like this:

dbItems = dbConnection.Interventions.Include(x => x.Persons.Car).ToList();

or for a nested list...

dbItems = dbConnection.Interventions.Include(x => x.Persons.Select(y => y.Cars).ToList();

or for multiple navigation properties...

dbItems = dbConnection.Interventions.Include(x => x.Persons)
                                    .Include(x => x.Cars).ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top