已经有与此连接关联的开放的DataReader,必须关闭第一+ asp.net mvc的 [英] There is already an open DataReader associated with this Connection which must be closed first + asp.net mvc

查看:383
本文介绍了已经有与此连接关联的开放的DataReader,必须关闭第一+ asp.net mvc的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表的entites 与它的多个字段,如ENTITY_TITLE,entity_description,... MySQL数据库。在表中也有3外键的 USER_ID REGION_ID CATEGORY_ID

在我的索引视图我想显示在一个表中的所有实体(显示标题,描述,......,用户名,区域名称和类别名称)。

这是我在我的控制器做的:

 公众的ActionResult指数()
{
    VAR模型= this.UnitOfWork.EntityRepository.Get();
    返回查看(模型);
}

在我的仓库我这样做:

 公共虚拟IEnumerable的< TEntity>得到(
    防爆pression<&Func键LT; TEntity,布尔>>过滤器= NULL,
    FUNC<&IQueryable的LT; TEntity>中IOrderedQueryable< TEntity>> ORDERBY = NULL,
    串includeProperties =)
{
    IQueryable的< TEntity>查询= _dbSet;    如果(过滤器!= NULL)
    {
        查询= query.Where(过滤器);
    }    在includeProperties.Split的foreach(VAR includeProperty
            (新的char [] {','},StringSplitOptions.RemoveEmptyEntries))
    {
        查询= query.Include(includeProperty);
    }    如果(排序依据!= NULL)
    {
        返回的OrderBy(查询).ToList();
    }
    其他
    {
        返回query.ToList();
    }
}

我总是得到错误输入字符串的不正确的格式上的最后一个规则(返回query.ToList())。

但是,当我检查_dbSet规则后的IQueryable< TEntity>查询= _dbSet; 它已经提供了错误:已经有与此连接,必须先关闭相关联的打开的DataReader

这可能来自,因为我想从一个以上的表中选择。但我怎么能解决这个问题?我尝试添加 MultipleActiveResultSets = TRUE我的ConnectionString是这样的:

 <&是connectionStrings GT;
<添加名称=reuzzeCS的connectionString =服务器=本地主机; UID =根; PWD = *****;坚持安全信息= TRUE;数据库= reuzze; MultipleActiveResultSets =真的providerName =MySql.Data.MySqlClient />

但是,这给我的关键字不存在的错误,因为我MySql.Data.MySqlClient ..

工作

执行的查询是:


  

{SELECT
   Extent1 ENTITY_ID
   Extent1 ENTITY_TITLE
   Extent1 entity_description
   Extent1 entity_starttime
   Extent1 entity_endtime
   Extent1 entity_instantsellingprice
   Extent1 entity_shippingprice
   Extent1 entity_condition
   Extent1 entity_views
   Extent1 entity_created
   Extent1 entity_modified
   Extent1 entity_deleted
   Extent1 USER_ID
   Extent1 REGION_ID
   Extent1 CATEGORY_ID
  FROM 实体 Extent1 }


但是,当他要执行查询,我想扩大成果,我得到的错误已经有与此连接,必须先关闭相关联的打开的DataReader

编辑:结果
我的完整存储库:

 使用系统;
使用System.Collections.Generic;
使用System.Data这;
使用System.Data.Entity的;
使用System.Linq的;
使用System.Linq.Ex pressions;
使用System.Text;
使用System.Threading.Tasks;命名空间App.Data.orm.repositories
{
// REPO从以教师
公共类GDMRepository< TEntity>其中,TEntity:类
{
    内部GDMContext _context;
    内部DbSet< TEntity> _dbSet;    公共GDMRepository(GDMContext上下文)
    {
        this._context =背景;
        this._dbSet = _context.Set< TEntity>();
    }    公共虚拟IEnumerable的< TEntity>得到(
        防爆pression<&Func键LT; TEntity,布尔>>过滤器= NULL,
        FUNC<&IQueryable的LT; TEntity>中IOrderedQueryable< TEntity>> ORDERBY = NULL,
        串includeProperties =)
    {
        IQueryable的< TEntity>查询= _dbSet;        如果(过滤器!= NULL)
        {
            查询= query.Where(过滤器);
        }        在includeProperties.Split的foreach(VAR includeProperty
            (新的char [] {','},StringSplitOptions.RemoveEmptyEntries))
        {
            查询= query.Include(includeProperty);
        }        如果(排序依据!= NULL)
        {
            返回的OrderBy(查询).ToList();
        }
        其他
        {
            返回query.ToList();
        }
    }    公共虚拟TEntity GetByID(对象ID)
    {
        返回_dbSet.Find(ID);
    }    公共虚拟无效插入(TEntity实体)
    {
        _dbSet.Add(实体);
    }    公共虚拟无效删除(对象ID)
    {
        TEntity entityToDelete = _dbSet.Find(ID);
        删除(entityToDelete);
    }    公共虚拟无效删除(TEntity实体)
    {
        如果(_context.Entry(实体).STATE == EntityState.Detached)
        {
            _dbSet.Attach(实体);
        }
        _dbSet.Remove(实体);
    }    公共虚拟无效更新(TEntity实体)
    {
        _dbSet.Attach(实体);
        _context.Entry(实体).STATE = EntityState.Modified;
    }
}
}

GDMContext类:

 使用App.Data.orm.mappings;
使用系统;
使用System.Collections.Generic;
使用System.Data.Entity的;
使用System.Data.Entity.ModelConfiguration.Conventions;
使用System.Linq的;
使用System.Text;
使用System.Threading.Tasks;命名空间App.Data.orm
{
公共类GDMContext:的DbContext
{
    公共GDMContext():基地(reuzzeCS){}    保护覆盖无效OnModelCreating(DbModelBuilder模型构建器)
    {
        base.OnModelCreating(模型构建器);        //移除标准映射实体框架
        modelBuilder.Conventions.Remove< PluralizingTableNameConvention>();        //注册映射器
        modelBuilder.Configurations.Add(新UserMapping());
        modelBuilder.Configurations.Add(新PersonMapping());
        modelBuilder.Configurations.Add(新RoleMapping());        modelBuilder.Configurations.Add(新EntityMapping());
        modelBuilder.Configurations.Add(新MediaMapping());
        modelBuilder.Configurations.Add(新BidMapping());
        modelBuilder.Configurations.Add(新CategoryMapping());
        modelBuilder.Configurations.Add(新AddressMapping());
        modelBuilder.Configurations.Add(新RegionMapping());
        modelBuilder.Configurations.Add(新MessageMapping());
    }
}
}

我的实体模型:

 公共类实体
{
    公众的Int64标识{搞定;组; }
    [必需(的ErrorMessage =必须输入标题)]
    [StringLength(255)]
    [显示名称(标题)
    公共字符串名称{搞定;组; }
    [必需(的ErrorMessage =说明要求)]
    [显示名称(说明)]
    公共字符串描述{搞定;组; }
    [需要]
    公共DateTime的开始时间{搞定;组; }
    [需要]
    公开日期时间结束时间{搞定;组; }
    / * [必填(的ErrorMessage =类型需要)]
    [StringLength(16)]
    [显示名称(类型)
    公共字符串类型{搞定;组; } * /
    [需要]
    公共小数InstantSellingPrice {搞定;组; }
    公众可空<&小数GT; ShippingPrice {搞定;组; }    公共条件?条件{搞定;组; }
    公众可空<&的Int64 GT;查看{搞定;组; }    [需要]
    公众的DateTime CREATEDATE {搞定;组; }
    公众可空<&日期时间GT; ModifiedDate {搞定;组; }
    公众可空<&日期时间GT; DeletedDate {搞定;组; }    公众的Int32用户ID {搞定;组; }    公众的Int32 RegionId {搞定;组; }    公众的Int16的CategoryId {搞定;组; }    公共虚拟用户用户{搞定;组; }
    公共虚拟地区地区{搞定;组; }
    公共虚拟分类分类{搞定;组; }
    //公共虚拟的ICollection<类别及GT;分类{搞定;组; }
    公共虚拟的ICollection<使用者>收藏{搞定;组; }
    公共虚拟的ICollection<出价>投标{搞定;组; }
    公共虚拟的ICollection<媒体和GT;媒体{搞定;组; }
}公共枚举条件
{
    新= 1,
    使用= 2
}

我的实体映射:

 内部类EntityMapping:EntityTypeConfiguration<实体GT;
{
    公共EntityMapping()
        :基地()
    {
        this.ToTable(实体,reuzze);        this.HasKey(T => t.Id);
        this.Property(T => t.Id)。.HasColumnName(ENTITY_ID)HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);        this.Property(T => t.Title)。.HasColumnName(ENTITY_TITLE)IsRequired()HasMaxLength(255)。
        this.Property(T => t.Description)。.HasColumnName(entity_description)IsRequired();
        this.Property(T => t.StartTime)。.HasColumnName(entity_starttime)IsRequired();
        this.Property(T => t.EndTime)。.HasColumnName(entity_endtime)IsRequired();
        //this.Property(t =方式> t.Type).HasColumnName(ENTITY_TYPE)IsRequired();
        this.Property(T => t.InstantSellingPrice)。.HasColumnName(entity_instantsellingprice)IsRequired();
        this.Property(T => t.ShippingPrice)。.HasColumnName(entity_shippingprice)IsOptional();
        this.Property(T => t.Condition)。.HasColumnName(entity_condition)IsRequired();
        this.Property(T => t.Views)。.HasColumnName(entity_views)IsOptional();
        this.Property(T => t.CreateDate).HasColumnName(\"entity_created\").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
        this.Property(T => t.ModifiedDate)。.HasColumnName(entity_modified)IsOptional();
        this.Property(T => t.DeletedDate)。.HasColumnName(entity_deleted)IsOptional();        this.Property(T => t.UserId)。.HasColumnName(USER_ID)IsRequired();
        this.Property(T => t.RegionId)。.HasColumnName(REGION_ID)IsRequired();
        this.Property(T => t.CategoryId)。.HasColumnName(CATEGORY_ID)IsRequired();        //外键映射
        this.HasRequired(T => t.User).WithMany(P => p.Entities).HasForeignKey(F => f.UserId).WillCascadeOnDelete(假);
        this.HasRequired(T => t.Region).WithMany(P => p.Entities).HasForeignKey(F => f.RegionId);
        this.HasRequired(T => t.Category).WithMany(P => p.Entities).HasForeignKey(F => f.CategoryId);        // MANY_TO_MANY映射
        this.HasMany(T => t.Favorites)
            .WithMany(T => t.Favorites)
            .MAP(MC =>
            {
                mc.ToTable(最爱);
                mc.MapLeftKey(ENTITY_ID);
                mc.MapRightKey(USER_ID);
            });
    }
}

链接到堆栈跟踪图像!

更新:


  

      
  • {基地选择
       Extent1 ENTITY_ID
       Extent1 ENTITY_TITLE
       Extent1 entity_description
       Extent1 entity_starttime
       Extent1 entity_endtime
       Extent1 entity_instantsellingprice
       Extent1 entity_shippingprice
       Extent1 entity_condition
       Extent1 entity_views
       Extent1 entity_created
       Extent1 entity_modified
       Extent1 entity_deleted
       Extent1 USER_ID
       Extent1 REGION_ID
       Extent1 CATEGORY_ID
      FROM 实体 Extent1 } {System.Data.Entity.Internal.Linq.InternalQuery System.Data.Entity.Internal .Linq.InternalSet}

  •   


解决方案

您的问题是


  

我想的MySQL Connector可能不支持多活动结果集,也因为在连接字符串中的设置也帮不了你。


所以请尝试,而不是你的code这样

编辑:

  query.Include(用户),包括(地区),包括(类别)了ToList()。;

让我知道,如果你这个更改后得到同样的错误。

更新:

我改变一些事情,你请使用,而不是你这个方法code

 公共虚拟IEnumerable的< TEntity>得到(
    防爆pression<&Func键LT; TEntity,布尔>>过滤器= NULL,
    FUNC<&IQueryable的LT; TEntity>中IOrderedQueryable< TEntity>> ORDERBY = NULL,
    串includeProperties =)
        {
            IQueryable的< TEntity>查询= _dbSet;            如果(过滤器!= NULL)
            {
                查询= query.Where(过滤器);
            }
            如果(排序依据!= NULL)
            {
                返回的OrderBy(query.Include(用户),包括(地区),包括(类别)了ToList()。)了ToList()。
            }
            其他
            {
                返回query.Include(用户),包括(地区),包括(类别)了ToList()。;
            }
        }

更新2:


  

这是不是关闭连接。 EF正确管理连接。我的这个问题的理解是,有上,而第一个已完成的读取之前执行下一DataReader的单一连接(或具有多个选择单命令)执行多个数据检索命令。为了避免异常的唯一方法是允许多个嵌套的DataReader =打开MultipleActiveResultSets。当这总是会发生的另一种情况是,当你通过查询(IQueryable的)结果迭代,你会触发延迟加载在迭代里面装的实体。


和堆栈溢出有很多人民得到了你的问题解决方案

1:<一href=\"http://stackoverflow.com/questions/4867602/entity-framework-there-is-already-an-open-datareader-associated-with-this-comma\">Entity框架:已经有一个用此命令相关联的打开的DataReader

2:<一href=\"http://stackoverflow.com/questions/6271971/how-to-avoid-there-is-already-an-open-datareader-associated-with-this-connectio\">How为了避免与QUOT;已经有与此连接,必须先关闭&QUOT相关联的打开的DataReader。在MySQL /网络接口?

3:<一href=\"http://stackoverflow.com/questions/15921821/error-there-is-already-an-open-datareader-associated-with-this-command-which-mu\">Error:已经有与此命令相关联的打开的DataReader,必须关闭第一

和我的个人建议,我认为你没有花更多的时间为这个错误,因为时间和精力的腰部,并且可以通过手动查询中使用做到这一点。所以,请尝试不同的方法。

您不必拆分和格式的查询,以避免输入字符串是不正确的格式错误

您可以做到这一点的方式,而不是返回query.ToList();

 收益_dbSet.Users
    .INCLUDE(X =&GT; x.Region)
    .INCLUDE(X =&GT; x.Category).ToList();

我觉得你可以用我上面 SO 链接的做到这一点。

和我的主要问题是:


  

实体框架可以支持ORM的概念,那么,为什么你不尝试这种方式?您可以更改使用ORM概念的想法。它们也可能是解决这个问题。 <一href=\"http://$c$ctunnel.com/blog/post/introduction-to-entity-framework-part-i-object-relational-mapping\"相对=nofollow>这对于一个链接,请请参见本教程


I have a mysql database with a table entites with multiple fields in it like entity_title, entity_description, ... . In the table there are also 3 foreign keys user_id, region_id an category_id.

In my Index View I would like to show all the entities in a table (show the title, description, ... , the user name, the region name and the category name).

This is what I do in my Controller:

public ActionResult Index()
{
    var model = this.UnitOfWork.EntityRepository.Get();
    return View(model);
}

In my Repository I do this:

public virtual IEnumerable<TEntity> Get(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    string includeProperties = "")
{
    IQueryable<TEntity> query = _dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
    {
        query = query.Include(includeProperty);
    }

    if (orderBy != null)
    {
        return orderBy(query).ToList();
    }
    else
    {
        return query.ToList();
    }
}

I always get the error Input string was not in a correct format on the last rule (return query.ToList()).

But when I check the _dbSet after the rule IQueryable<TEntity> query = _dbSet; it already gives the error: There is already an open DataReader associated with this Connection which must be closed first.

This probably comes because I want to select from more then one table. But how can I fix this? I tried adding MultipleActiveResultSets=True" to my ConnectionString like this:

<connectionStrings>
<add name="reuzzeCS" connectionString="server=localhost;uid=root;pwd=*****;Persist Security Info=True;database=reuzze;MultipleActiveResultSets=True"" providerName="MySql.Data.MySqlClient" />

But that gave me the error that the keyword doesn't exists, because I work with MySql.Data.MySqlClient ..

The Query executed is:

{SELECT Extent1.entity_id, Extent1.entity_title, Extent1.entity_description, Extent1.entity_starttime, Extent1.entity_endtime, Extent1.entity_instantsellingprice, Extent1.entity_shippingprice, Extent1.entity_condition, Extent1.entity_views, Extent1.entity_created, Extent1.entity_modified, Extent1.entity_deleted, Extent1.user_id, Extent1.region_id, Extent1.category_id FROM entities AS Extent1}

But when he wants to execute the query and I want to expand the results, I get the error There is already an open DataReader associated with this Connection which must be closed first

EDIT:
My full repository:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace App.Data.orm.repositories
{
// REPO FROM TEACHER
public class GDMRepository<TEntity> where TEntity : class
{
    internal GDMContext _context;
    internal DbSet<TEntity> _dbSet;

    public GDMRepository(GDMContext context)
    {
        this._context = context;
        this._dbSet = _context.Set<TEntity>();
    }

    public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = _dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

    public virtual TEntity GetByID(object id)
    {
        return _dbSet.Find(id);
    }

    public virtual void Insert(TEntity entity)
    {
        _dbSet.Add(entity);
    }

    public virtual void Delete(object id)
    {
        TEntity entityToDelete = _dbSet.Find(id);
        Delete(entityToDelete);
    }

    public virtual void Delete(TEntity entity)
    {
        if (_context.Entry(entity).State == EntityState.Detached)
        {
            _dbSet.Attach(entity);
        }
        _dbSet.Remove(entity);
    }

    public virtual void Update(TEntity entity)
    {
        _dbSet.Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
    }
}
}

GDMContext class:

using App.Data.orm.mappings;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace App.Data.orm
{
public class GDMContext:DbContext
{
    public GDMContext() : base("reuzzeCS") { }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        //REMOVE STANDARD MAPPING IN ENTITY FRAMEWORK
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        //REGISTER MAPPERS
        modelBuilder.Configurations.Add(new UserMapping());
        modelBuilder.Configurations.Add(new PersonMapping());
        modelBuilder.Configurations.Add(new RoleMapping());

        modelBuilder.Configurations.Add(new EntityMapping());
        modelBuilder.Configurations.Add(new MediaMapping());
        modelBuilder.Configurations.Add(new BidMapping()); 
        modelBuilder.Configurations.Add(new CategoryMapping());
        modelBuilder.Configurations.Add(new AddressMapping());
        modelBuilder.Configurations.Add(new RegionMapping()); 
        modelBuilder.Configurations.Add(new MessageMapping());
    }
}
}

My entity Model:

public class Entity
{
    public Int64 Id { get; set; }
    [Required(ErrorMessage = "Title is required")]
    [StringLength(255)]
    [DisplayName("Title")]
    public string Title { get; set; }
    [Required(ErrorMessage = "Description is required")]
    [DisplayName("Description")]
    public string Description { get; set; }
    [Required]
    public DateTime StartTime { get; set; }
    [Required]
    public DateTime EndTime { get; set; }
    /*[Required(ErrorMessage = "Type is required")]
    [StringLength(16)]
    [DisplayName("Type")]
    public string Type { get; set; }*/
    [Required]
    public decimal InstantSellingPrice { get; set; }
    public Nullable<decimal> ShippingPrice { get; set; }

    public Condition? Condition { get; set; }
    public Nullable<Int64> Views { get; set; }

    [Required]
    public DateTime CreateDate { get; set; }
    public Nullable<DateTime> ModifiedDate { get; set; }
    public Nullable<DateTime> DeletedDate { get; set; }

    public Int32 UserId { get; set; }

    public Int32 RegionId { get; set; }

    public Int16 CategoryId { get; set; }

    public virtual User User { get; set; }
    public virtual Region Region { get; set; }
    public virtual Category Category { get; set; }
    //public virtual ICollection<Category> Categories { get; set; }
    public virtual ICollection<User> Favorites { get; set; }
    public virtual ICollection<Bid> Bids { get; set; }
    public virtual ICollection<Media> Media { get; set; }
}

public enum Condition
{
    New = 1,
    Used = 2
}

My Entity Mapping:

internal class EntityMapping : EntityTypeConfiguration<Entity>
{
    public EntityMapping()
        : base()
    {
        this.ToTable("entities", "reuzze");

        this.HasKey(t => t.Id);
        this.Property(t => t.Id).HasColumnName("entity_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        this.Property(t => t.Title).HasColumnName("entity_title").IsRequired().HasMaxLength(255);
        this.Property(t => t.Description).HasColumnName("entity_description").IsRequired();
        this.Property(t => t.StartTime).HasColumnName("entity_starttime").IsRequired();
        this.Property(t => t.EndTime).HasColumnName("entity_endtime").IsRequired();
        //this.Property(t => t.Type).HasColumnName("entity_type").IsRequired();
        this.Property(t => t.InstantSellingPrice).HasColumnName("entity_instantsellingprice").IsRequired();
        this.Property(t => t.ShippingPrice).HasColumnName("entity_shippingprice").IsOptional();
        this.Property(t => t.Condition).HasColumnName("entity_condition").IsRequired();
        this.Property(t => t.Views).HasColumnName("entity_views").IsOptional();
        this.Property(t => t.CreateDate).HasColumnName("entity_created").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
        this.Property(t => t.ModifiedDate).HasColumnName("entity_modified").IsOptional();
        this.Property(t => t.DeletedDate).HasColumnName("entity_deleted").IsOptional();

        this.Property(t => t.UserId).HasColumnName("user_id").IsRequired();
        this.Property(t => t.RegionId).HasColumnName("region_id").IsRequired();
        this.Property(t => t.CategoryId).HasColumnName("category_id").IsRequired();

        //FOREIGN KEY MAPPINGS
        this.HasRequired(t => t.User).WithMany(p => p.Entities).HasForeignKey(f => f.UserId).WillCascadeOnDelete(false);
        this.HasRequired(t => t.Region).WithMany(p => p.Entities).HasForeignKey(f => f.RegionId);
        this.HasRequired(t => t.Category).WithMany(p => p.Entities).HasForeignKey(f => f.CategoryId);

        //MANY_TO_MANY MAPPINGS
        this.HasMany(t => t.Favorites)
            .WithMany(t => t.Favorites)
            .Map(mc =>
            {
                mc.ToTable("favorites");
                mc.MapLeftKey("entity_id");
                mc.MapRightKey("user_id");
            });
    }
}

Link to stacktrace image!

UPDATE:

  • base {SELECT Extent1.entity_id, Extent1.entity_title, Extent1.entity_description, Extent1.entity_starttime, Extent1.entity_endtime, Extent1.entity_instantsellingprice, Extent1.entity_shippingprice, Extent1.entity_condition, Extent1.entity_views, Extent1.entity_created, Extent1.entity_modified, Extent1.entity_deleted, Extent1.user_id, Extent1.region_id, Extent1.category_id FROM entities AS Extent1} System.Data.Entity.Internal.Linq.InternalQuery {System.Data.Entity.Internal.Linq.InternalSet}

解决方案

Your problem is

I think MySql connector probably doesn't support multiple active result sets and because of that the setting in connection string didn't help you.

So Please try this way instead of your code

Edit :

query.Include("User").Include("Region").Include("Category").ToList(); 

Let me know, if you get same error after this change.

Update:

I have change some thing for you Please use this code instead of your method

 public virtual IEnumerable<TEntity> Get(
    Expression<Func<TEntity, bool>> filter = null,
    Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
    string includeProperties = "")
        {
            IQueryable<TEntity> query = _dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }


            if (orderBy != null)
            {
                return orderBy(query.Include("User").Include("Region").Include("Category").ToList()).ToList();
            }
            else
            {
                return query.Include("User").Include("Region").Include("Category").ToList(); 
            }
        }

Update 2:

It is not about closing connection. EF manages connection correctly. My understanding of this problem is that there are multiple data retrieval commands executed on single connection (or single command with multiple selects) while next DataReader is executed before first one has completed the reading. The only way to avoid the exception is to allow multiple nested DataReaders = turn on MultipleActiveResultSets. Another scenario when this always happens is when you iterate through result of the query (IQueryable) and you will trigger lazy loading for loaded entity inside the iteration.

And stack overflow have lot of peoples got the solutions for your question

1: Entity Framework: There is already an open DataReader associated with this Command

2: How to avoid "There is already an open DataReader associated with this Connection which must be closed first." in MySql/net connector?

3: Error: There is already an open DataReader associated with this Command which must be closed first

and my personal advice for, I think you don't spent more time for this error, because waist of time and energy , and you can do it by using by manual query . So please try different ways.

You don't need split and formatting queries for avoiding input string was not correct format error

You can do this way instead of return query.ToList();

return _dbSet.Users
    .Include(x => x.Region)
    .Include(x => x.Category).ToList();

I think you can do it by using my above SO link's.

And My main question is :

Entity Framework can support ORM Concept, So why you don't try this way?. You can change the idea for using ORM Concept. It's may be solve this problem. This is a link for that and please see this tutorial

这篇关于已经有与此连接关联的开放的DataReader,必须关闭第一+ asp.net mvc的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆