Nul*_*nce 12 .net c# entity-framework linq-to-sql
我有以下代码从客户表中检索数据
var customers= context.CustomerEntities.Include("Addresses").Select(Mapper.Map).ToList();
Run Code Online (Sandbox Code Playgroud)
映射器函数将实体对象映射到业务对象,它看起来像这样
internal static Customer Map(CustomerEntity entity)
{
if (entity == null)
return null;
return new Customer
{
Id = entity.Id,
Name = entity.Name,
Addresses = Map(entity.Addresses)
};
}
Run Code Online (Sandbox Code Playgroud)
现在,上面的代码运行良好.
但是,当我尝试这样做时:
var customers= context.CustomerEntities.Select(Mapper.Map).ToList();
Run Code Online (Sandbox Code Playgroud)
我收到错误消息:There is already an open DataReader associated with this Command which must be closed first执行Mapper函数时.
现在我知道要解决这个问题,我必须multipleactiveresultsets=True在我的连接字符串中设置.我试过了,它确实解决了我的问题.
但是,当我运行SQL事件探查器时,从实体框架查询所有客户也会自动检索所有地址,即使我不需要它们.
除了必须设置之外还有解决方法multipleactiveresultsets=True吗?我不希望地址一直延迟加载.
Dan*_*nex 14
我相信这是因为每个Customerselect语句都会导致再次读取数据库.你为什么不先做ToList(),然后应用映射(Select)类似于:
var customers= context.CustomerEntities.ToList().Select(Mapper.Map);
Run Code Online (Sandbox Code Playgroud)
我相信这会首先带来数据,然后进行映射,你就不会遇到这个问题.