【发布时间】:2018-06-16 16:29:31
【问题描述】:
在数据访问层的方法中返回 DbContext 查询的结果时遇到问题。我正在这样做:
public IEnumerable<Person> GetAllPeople()
{
IEnumerable<Person> people;
using (var context = new AdressingContext())
{
people = context.People.ToList();
}
return people;
}
当我想在 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();
}
}
抛出异常
操作无法完成,因为 DbContext 已被释放。
我知道在 using 块的最后,里面创建的对象被释放了,但不应该
people = context.People;
复制那些对象?你能提出一个优雅的方法来解决这个问题吗?
编辑:Person.ToString() 在if() 语句中抛出异常。
ObjectContext 实例已被释放,不能再用于需要连接的操作。
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}";
}
【问题讨论】:
-
你真的在那里使用
people = context.People.ToList()吗?或者只是people = context.People,就像你最后一段代码摘录中的那样? -
当调用
ToList()时,EF 会将值加载到内存集合中。 -
什么是
ContactInformation?这可能是与您的Person类型相关联的另一个实体吗?在这种情况下,你将不得不做context.People.Include(p => p.ContactInformation).ToList() -
是的,我用的是people = context.People.ToList(),但还是有异常。
-
正确,ContactInformation 是另一个链接到 Person 类型的实体,但您的代码没有编译,因为它说 p => p.ContactInformation 不能从 lambda 转换为字符串
标签: c# entity-framework