我目前在正在调用的EF方法中遇到此错误(已经让Elmah工作)
不允许使用新事务,因为会话中还有其他线程在运行。
我看过这个:
和类似的问题,但这些都是指在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仍然保持打开连接?