c# – 实体框架已经有一个与此命令关联的开放DataReader,必须先关闭它
作者:互联网
我正在努力解决上面的错误.我在这里发现了不同的答案(堆栈溢出),但它们都没有解决我与错误相关的问题.
我只是在我的ConnectionString中启用MARS但没有成功.
我有一类产品
public class Product
{
public Product()
{
this.Additives = new HashSet<Additive>();
}
public int Id { get; set; }
public string Name { get; set; } // refrigerante
public string CommercialName { get; set; } // nome popular, ex: fanta laranja
public string Brand { get; set; } // marca, ex: Coca-cola
public string Details { get; set; } // composicao, ingredientes
public HalalState HalalState { get; set; } // estado: halal, haram ou desconhecido
public DateTime? LastUpdate { get; set; } // date e hora do registo
public virtual ICollection<Additive> Additives { get; set; } // aditivos
public int ProviderID { get; set; }
}
}
和类添加剂代表产品中的添加剂
using System;
using System.Collections.Generic;
namespace Teknowhow.EatHalal.Core.Models
{
public class Additive
{
public Additive()
{
this.Products = new HashSet<Product>();
}
public int Id { get; set; }
public string Key { get; set; } // codigo ex: E130
public string NamePT { get; set; } // nome ex: Acido ascorbico (Vitamina C) em portugues
public string NameEN { get; set; } // nome ex: Acido ascorbico (Vitamina C) em inglês
public string Details { get; set; } // detalhes sobre o aditivo, incluindo.
public HalalState HalalState; // estado: halal, haram ou desconhecido
public DateTime? LastUpdate { get; set; } // date e hora do registo
public virtual ICollection<Product> Products { get; set;}
}
}
我正在编写一个代码来实现ProductRepository上的方法,以便获得具有特定添加剂的产品.
public ICollection<Product> GetProductsByAdditive(string key)
{
var products = context.Products;
var productsAdditives = new List<Product>();
foreach (var p in products)
{
var additives = p.Additives;
foreach (var a in additives)
{
if (a.Key.Equals(key))
productsAdditives.Add(p);
}
}
return productsAdditives.ToList();
//TODO: um Metodo úinico que permite pesquisa por nome em PT e EN e codigo
}
错误发生在第一个foreach循环之后,在此语句上:
var additives = p.Additives;
PS:我正在使用EF 6.
我堆积了!请帮忙!
继承人我的联系
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="EatHalal"
providerName="System.Data.SqlClient"
connectionString="Server=192.168.1.150;Database=EatHalal;User Id=user;Password=password;MultipleActiveResultSets=true;"
/>
</connectionStrings>
</configuration>
解决方法:
context.Products.Where(x=>x.Additives.Any(y=>y.Key==key)).ToList();
你的代码失败了,因为你在添加产品时懒惰加载添加剂……
但是itteration本身是无稽之谈…如果你想在数据库中搜索某些东西,让数据库通过给它搜索一些东西来完成它的工作,而不是告诉它给你所有东西,然后整理出你想要的东西. ..
想象一下,如果你的桌子里会有几亿件产品……
你会加载所有产品并经历多年…
看看LINQ
看看.Where()
看看.选择()
熟悉lambda表达式
标签:c,sql-server,entity-framework,lazy-loading,eager-loading 来源: https://codeday.me/bug/20190716/1475042.html