Search code examples
c#entity-frameworkwcfdbcontextusing

EF returns ExecuteReader requires an open and available Connection. The connection's current state is open. error


I have a lot of classes with this structure as you can see:

 public class OrganizationUserRepository : IOrganizationUserRepository
    {
        private  DataContext _ctx;

        public OrganizationUserRepository(DataContext ctx)
        {
            _ctx = ctx;
        }
        public bool Add(OrganizationUser entity)
        {
            try
            {
                _ctx.OrganizationUsers.Add(entity);
                _ctx.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }

        public bool Edit(OrganizationUser entity)
        {
            try
            {
                OrganizationUser Edited = _ctx.OrganizationUsers.Where(i => i.Id == entity.Id).First();
                _ctx.Entry(Edited).CurrentValues.SetValues(entity);
                _ctx.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }



        public bool Remove(string id)
        {
            try
            {
                Int64 Id = Int64.Parse(id);
                OrganizationUser obj = _ctx.OrganizationUsers.Where(i => i.Id == Id).First();
                _ctx.OrganizationUsers.Remove(obj);
                _ctx.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                // TODO log this error
                return false;
            }
        }


    }

The db context in constructor is injected by ninject .as you can see it just one of my classes .and i have multi classes like this in another services that use a single DB .(WCF Service).But i get this error in my wcf tracelog :

ExecuteReader requires an open and available Connection. The connection's current state is open.

I am using EF code first .

I found this Wrap DbContext db = new DbContext() inusing statement. And i want to know should i use this ,if Yes how can i change my class structure to use using in my code ?


Solution

  • I used public Readonly DbContext .i just remove readonly and everything work fine.