在EF数据库连接错误 [英] Database connection errors on EF

查看:195
本文介绍了在EF数据库连接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很新的实体框架和我有,我正在写一个web API基础的网站(连接MSSQL)中的问题。我不断收到看似随意的错误(主要是似乎是与数据库相关的)。当站点首次公布,但是当它一直小时自上次发布但有时也会发生最常这些错误发生。错误的选择:

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 seeming to be database related). These errors happen most often when the site is first published but they do sometimes happen when it has been hours since the last publish. A selection of the errors:


      
  • 操作无效。连接被关闭。

  •   
  • 已经有一个用此命令,必须先关闭相关联的打开的DataReader。

  •   
  • 连接没有关闭。连接的当前状态进行连接。

  •   
  • 正在创建的模型,而上下文无法查看

  •   
  • 基础提供程序未能打开

  •   

我的背景是这样的:

public class Context : DbContext
{

    public Context() : base("name=DefaultConnection")
    {
    }

    public override int SaveChanges()
    {
        DateTime now = DateTime.Now;
        foreach (ObjectStateEntry entry in (this as IObjectContextAdapter).ObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
        {
            if (!entry.IsRelationship)
            {
                IHasUpdated updated = entry.Entity as IHasUpdated;
                if (updated != null)
                    updated.updated = now;
            }
        }
        return base.SaveChanges();
    }

    public DbSet<Branch> Branches { get; set; }
    public DbSet<Company> Companies { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<UsefulLink> UsefulLinks { get; set; }
}

有很多比这更DbSets。我应该创建为每个单独的上下文?

There are many more DbSets than this. Should I be creating a separate context for each?

我的一个基本的控制器:

One of my basic controllers:

 public class UsefulLinksController : ApiController
 {
    private Context db = new Context();

    [ResponseType(typeof(UsefulLinksWrapper))]
    public IHttpActionResult GetUsefulLinks([FromUri]UsefulLinkParams prams)
    {   
        UsefulLinksWrapper wrapper = new UsefulLinksWrapper();
        Meta meta = new Meta();
        IQueryable<UsefulLink> query = db.UsefulLinks;

    if (prams.sortBy == null)
        {
            prams.sortBy = "ID";
        }

        // Paging
        query = query.OrderBy(prams.sortBy + " " + prams.sortDirection).Skip(prams.offset - 1).Take(prams.limit);

        List<UsefulLink> data = query.ToList();

        meta.totalCount = query.Count();
        meta.offset = 1;
        meta.limit = prams.limit;
        wrapper.meta = meta;
        wrapper.data = data;

        return Ok(wrapper);

    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

    private bool UsefulLinkExists(int id)
    {
        return db.UsefulLinks.Count(e => e.ID == id) > 0;
    }
}

我似乎没有看到这些错误,当我在本地运行的网站虽然有我们两个人打它发布时也许这样的问题,来自多个用户的茎?

I don't seem to see these errors when I run the site locally though there are two of us hitting it when it is published so perhaps the issue stems from multiple users?

推荐答案

克里斯,我注意到在您的控制器,你与所有的控制器类中的方法分享你的数据库环境。

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

这通常不是在实体框架(参见最佳实践:<一href=\"http://stackoverflow.com/questions/3362280/entity-framework-4-objectcontext-lifetime\">EntityFramework 4 ObjectContext的终身)。你应该让你的背景下活着尽可能简短。活着离开跨越多种方法来共享的背景下,可能会导致许多你上面列出的错误。

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.

所以下面的:

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

   public someMethod2()
   {
      context.doSomething;
   }
}

应该变成:

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.

这篇关于在EF数据库连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆