I've got a problem with returning the result of DbContext query in a method of data access layer. I'm doing this:
public IEnumerable<Person> GetAllPeople()
{
IEnumerable<Person> people;
using (var context = new AdressingContext())
{
people = context.People.ToList();
}
return people;
}
And when I want to print the output in Main:
class Program
{
static void Main(string[] args)
{
ContactsRepository repository = new ContactsRepository();
var people = repository.GetAllPeople();
foreach (var item in people)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
The exception is thrown
The operation cannot be completed because the DbContext has been disposed.
I know that in the end of using block the objects created inside are disposed, but shouldn't
people = context.People;
copy those objects? Could you propose an elegant way to solve this?
Edit: exception is thrown in Person.ToString()
in if()
statement.
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
public override string ToString()
{
if (ContactInformation == null)
{
return $"PersonId={PersonId}, FirstName={FirstName}, LastName={LastName}, Sex={Sex}, Birthday={Birthday}, Description: {Description}";
}
return $"PersonId={PersonId}, FirstName={FirstName}, LastName={LastName}, Sex={Sex}, Birthday={Birthday}, Contact: {ContactInformation.ToString()}, Description: {Description}";
}