Database connection errors on EF

前端 未结 2 420
别那么骄傲
别那么骄傲 2021-01-24 09:09

I am very new to entity framework and I am having a problem with a web api based site (connected to mssql) that I am writing. I keep getting seemingly random errors (mostly seem

2条回答
  •  情书的邮戳
    2021-01-24 09:44

    Chris, I notice in your controller you are sharing your db context with all of the methods in your controller class.

    This is generally not a best practice in Entity Framework (see: EntityFramework 4 ObjectContext Lifetime). You should keep your context alive as briefly as possible. Leaving the context alive to share across multiple methods could result in many of the errors that you list above.

    I would recommend trying to instantiate a new instance of the context, instead, wherever it is used and quickly disposing of it.

    This should generally result in more stable behavior.

    So the below:

    class SomeClass
    {
       private context = new Context(); //sharing your context with all methods
       public someMethod()
       {
          context.doSomething;
       }
    
       public someMethod2()
       {
          context.doSomething;
       }
    }
    

    should become:

    class SomeClass
    {
    
       public someMethod()
       {
          Context context = new Context(); //now your context is declared and disposed of within each method
          context.doSomething;
       }
    
       public someMethod2()
       {
          Context context = new Context(); //now your context is declared and disposed of within each method
          context.doSomething;
       }
    }
    

    Or even better, you can use a using construct to ensure that your context is properly disposed of:

    class SomeClass
    {
       public someMethod3()
       {
          using(Context context = new Context()) //now wrapping the context in a using to ensure it is disposed
          {
             context.doSomething;
          }
       }
    }
    

    I would recommend trying the above changes and seeing if your behavior becomes more stable.

提交回复
热议问题