如何修复 连接未关闭。连接的当前状态是正在连接吗?

在我开始我的项目之前,我没有收到任何错误,但是当我启动它时,我收到此错误


连接未关闭。连接的当前状态为正在连接。


错误在这段代码中


public class RoleMenu{

   private DBContext db = new DBContext();

   public List<Menu> GetList_Menu_ByRole(Role role)

   {

        List<RoleMenu> roleMenus = db.RoleMenus.Include(u => u.Role).Include(u => u.Menu).ToList(); //error is here

        List<Menu> roles = new List<Menu>();

        foreach (var eachRoleMenu in roleMenus)

        {

              if (eachRoleMenu.RoleID == role.ID)

              {

                  roles.Add(eachRoleMenu.Menu);

              }

        }

        return roles;

  }

}

这是我的 web.config


  <add name="DBContext" connectionString="Data Source=DESKTOP-SRRO03Q;Initial Catalog=Project1;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

如何修复这个错误?谢谢,


慕尼黑8549860
浏览 117回答 1
1回答

慕尼黑的夜晚无繁华

这仍然没有显示正确的错误源,但一般来说,我永远不会保留 a 的私有变量DBContext,除非在非常罕见的情况下。您需要让您的类RoleMenu实现IDisposable并正确使用它。我建议您每个查询使用一个上下文,如下所示:public class RoleMenu{&nbsp; &nbsp; public List<Menu> GetList_Menu_ByRole(Role role)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; using (DBContext db = new DBContext())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<RoleMenu> roleMenus = db.RoleMenus.Include(u => u.Role).Include(u => u.Menu).ToList(); //error is here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; List<Menu> roles = new List<Menu>();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foreach (var eachRoleMenu in roleMenus)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (eachRoleMenu.RoleID == role.ID)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; roles.Add(eachRoleMenu.Menu);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return roles;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP