Database connection errors on EF

前端 未结 2 388
别那么骄傲
别那么骄傲 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:41

    Since I do not know how your page uses the methods UsefulLinksController and in which order, I would say UsefulLinkExists is perhaps the culprit due to lazy loading

    Lazy loading means delaying the loading of related data until you specifically request it

    Which would explain why your "reader" remains "open".

    Try:

    return db.UsefulLinks.ToList().Count(e => e.ID == id) > 0;
    

    In any case, you can disable lazy loading by default in the context constructor as such noted here:

    public MyEntitiesContext() : base("name=MyEntitiesContext", "MyEntitiesContext")
    {
        this.ContextOptions.LazyLoadingEnabled = false;
        OnContextCreated();
    }
    

    As far as I know, it applies to EF4 and up.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题