C# entityframework 已经有一个与此命令关联的打开的 DataReader 必须先关闭

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16065684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:53:53  来源:igfitidea点击:

entityframework There is already an open DataReader associated with this Command which must be closed first

c#.netentity-frameworklinq-to-sql

提问by Null Reference

I have the following code that retrieves data from a customer table

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

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

The mapper function, maps the entity object, to a business object, and it looks like this

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

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

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

        };
    }

Now, the above code runs well.

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

However, when I try to do this:

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

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

I get the error message: There is already an open DataReader associated with this Command which must be closed firstwhen the Mapper function is being executed.

我收到错误消息:There is already an open DataReader associated with this Command which must be closed first正在执行 Mapper 函数时。

Now I'm aware that to solve this problem, I have to set multipleactiveresultsets=Truein my connection string. I have tried it, and it did solve my problem.

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

However, when I ran SQL profiler, querying all customers from entity framework automatically retrieved all the addresses as well, even though I didn't need them.

但是,当我运行 SQL 探查器时,从实体框架查询所有客户也会自动检索所有地址,即使我不需要它们。

Is there a workaround besides having to set multipleactiveresultsets=True? I don't want the addresses to be lazy loaded all the time.

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

采纳答案by Dan Hunex

I believe that is because for each Customerthe select statement is causing to go and read the database again. Why don't you do first ToList()and then apply the mapping (Select) something like:

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

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

I believe this would bring the data first and then do the mapping and you wouldn't have that issue.

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