Gaoxin Huang
Gaoxin Huang

Reputation: 198

EntityException occurred in EntityFramework.SqlServer.dll

My Controller code

   ParaEntities db = new ParaEntities();
    public List<Client> GetAllClients()
    {
        return db.Client.ToList();
    }

Please click this link to see the error message

It is weird that when I am first time to click the button to get all client information then it responses 500. In the second time, I click the button to get all client, which is success.

Upvotes: 1

Views: 2147

Answers (3)

Marcus H&#246;glund
Marcus H&#246;glund

Reputation: 16801

This error points to a connection problem rather then code issue. Check that the connectionstring is valid and that the user specified in the connectionstring has access to the database. If you're running the application on IIS then make sure that the applicationpool user has access to the database. Here is another SO issue were they solved this error.

If you want to store the db context as a local variable in your controller class then I suggest you to instantiate it inside of the controllers constructor. Then you make sure that every time a instance of the controller is created then a new db context is created as well. Lets say your controller namned ClientController

private ParaEntities db;
public ClientController()
{
    this.db = new ParaEntities();
}

public List<Client> GetAllClients()
{
   return db.Client.ToList();
}

Another approach is to wrap your db context in a using statment inside of your method. In that case you make sure that the method is using a fresh context when being called upon and that the context is being disposed when the operation is completed.

public List<Client> GetAllClients()
{
    using(ParaEntities db = new ParaEntities())
    {
       return db.Client.ToList();
    }
}

PS: both examples violates the dependency inversion principle (hard coupling to the db context) but thats for another day

Upvotes: 0

arunraj770
arunraj770

Reputation: 827

Please try this

public List<Client> GetAllClients() { ParaEntities db = new ParaEntities(); return db.Client.ToList(); }

Upvotes: 0

Prerak Acharya
Prerak Acharya

Reputation: 124

You should assign variable and display the data in View. Please change the syntax as i write below.

ParaEntities db = new ParaEntities();
public List<Client> GetAllClients()
{
    var getData= db.Client.ToList();
       if(getData==null)
           {
               return null;
            }
    return getData;
}

Upvotes: 1

Related Questions