C# 返回实体框架查询的结果
在数据访问层的方法中返回DbContext查询的结果时遇到问题。我正在这样做:C# 返回实体框架查询的结果,c#,entity-framework,C#,Entity Framework,在数据访问层的方法中返回DbContext查询的结果时遇到问题。我正在这样做: public IEnumerable<Person> GetAllPeople() { IEnumerable<Person> people; using (var context = new AdressingContext()) { people = context.People.ToList(); } return people
public IEnumerable<Person> GetAllPeople()
{
IEnumerable<Person> people;
using (var context = new AdressingContext())
{
people = context.People.ToList();
}
return people;
}
异常被抛出
无法完成该操作,因为DbContext已被释放
我知道在使用block的最后,内部创建的对象会被处理,但不应该
people = context.People;
复制那些对象?你能提出一个优雅的方法来解决这个问题吗
编辑:异常在if语句中的Person.ToString中引发
ObjectContext实例已被释放,不能再用于需要连接的操作
您已启用延迟加载,并且正在从另一个表的导航属性获取信息。因此,当您访问该数据时,它将尝试加载该数据,但您已经处理了上下文。使用.include或关闭延迟加载。您真的在使用people=context.people.ToList吗?或者只是people=context。在您的最后一段代码摘录中的people?调用ToList时,EF会将值加载到内存集合中。什么是ContactInformation?这可能是另一个链接到您的个人类型的实体吗?在这种情况下,您必须执行context.People.Includep=>p.ContactInformation.ToList是的,我使用的是People=context.People.ToList,但仍然存在一个异常。正确,ContactInformation是另一个链接到Person type的实体,但是您的代码没有编译,因为它说p=>p.ContactInformation不能从lambda转换为string
people = context.People;
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}";
}