gpt4 book ai didi

c# - entityframework 已经有一个与此命令关联的打开的 DataReader,必须先将其关闭

转载 作者:可可西里 更新时间:2023-11-01 08:23:24 26 4
gpt4 key购买 nike

我有以下代码从客户表中检索数据

var customers= context.CustomerEntities.Include("Addresses").Select(Mapper.Map).ToList();

映射器函数,将实体对象映射到业务对象,看起来像这样

    internal static Customer Map(CustomerEntity entity)
{
if (entity == null)
return null;

return new Customer
{
Id = entity.Id,
Name = entity.Name,
Addresses = Map(entity.Addresses)

};
}

现在,上面的代码运行良好。

但是,当我尝试这样做时:

var customers= context.CustomerEntities.Select(Mapper.Map).ToList();

我收到错误消息:在执行 Mapper 函数时,已经有一个打开的 DataReader 与此命令关联,必须先将其关闭

现在我知道要解决这个问题,我必须在我的连接字符串中设置 multipleactiveresultsets=True。我试过了,确实解决了我的问题。

但是,当我运行 SQL 分析器时,从 Entity Framework 查询所有客户也会自动检索所有地址,即使我不需要它们。

除了必须设置 multipleactiveresultsets=True 之外,还有解决方法吗?我不希望地址一直延迟加载。

最佳答案

我相信这是因为对于每个 Customer,select 语句都会导致再次读取数据库。为什么不先执行 ToList() 然后应用映射(Select),例如:

var customers= context.CustomerEntities.ToList().Select(Mapper.Map);

我相信这会先带来数据,然后再进行映射,您不会遇到这个问题。

关于c# - entityframework 已经有一个与此命令关联的打开的 DataReader,必须先将其关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16065684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com