实体框架错误 - 不允许新事务

时间:2017-12-06 10:32:13

标签: c# entity-framework linq

我目前在正在调用的EF方法中遇到此错误(已经让Elmah工作)

  

不允许使用新事务,因为会话中还有其他线程在运行。

我看过这个:

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

和类似的问题,但这些都是指在foreach循环中调用savechanges。我的代码没有 foreach循环,所以我很难找到问题。

控制器(继承自ApiController)

static readonly IMyRepository myRepository = new MyRepository();

public HttpResponseMessage PutObject(int id, int id2)
{
    if(!myRepository.Update(id,id2))
    {
        return Request.CreateErrorResponse(HttpStatusCode.NotFound);
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

存储库

MyEntities _myEntities;

public MyRepository(MyEntities context)
{
    _myEntities = context;
}

public MyRepository()
{

}

    public bool Update(int id,int id2, string id3, int id4)
    {
        _myEntities = _myEntities ?? new MyEntities();

        //update by id if id2,id3 and id4 are zero
        if (id2 == 0 && id3 == "0" && id4 == 0)
        {
            var myobject = _myEntities.MyObjects.Where(x => x.id == id);
            if (myobject.Count() > 0)
            {
                MyObject temp = myobject.SingleOrDefault();
                temp.Processed = true;
                _myEntities.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            var myobject = _myEntities.MyObjects.Where(x => x.SourceID == id && x.ExternalID == id2 && x.InternalID == id3 && x.Code == id4 && x.Processed == false);
            if (myobject.Count() > 0)
            {
                myobject temp = myobject.SingleOrDefault();
                temp.Processed = true;
                _myEntities.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }
    }

这是因为linq返回的IQueryable仍然保持打开连接?

0 个答案:

没有答案