使用FirstOrDefault时出现InvalidOperationException

时间:2015-08-05 14:20:38

标签: c# asp.net webforms entity-framework-6.1

我使用的是EF6.1.3,.NET 4.6和Web窗体。我刚刚更新到Windows 10和Visual Studio 2015,所以它可能不是代码而是完全不同的东西,但此时我真的不知道为什么会这样。

仅针对这一个实体,当我没有调试并更改值时,值会更改,但如果我尝试删除该实体,则实体将恢复为旧值并继续执行代码。

如果我正在调试并逐步通过代码,我会在FirstOrDefault上遇到此异常:

System.InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

删除代码非常简单:

protected void btnDelete_OnClick(object sender, EventArgs e)
{
    using (IContext db = new DatabaseContext(Session["cn"].ToString()))
    {
        var objId = new Guid(Request.QueryString["id"]);
        var obj = db.Objects.FirstOrDefault(x => x.Id == objId);
        db.Objects.Remove(obj);
        db.SaveChanges();
        Response.Redirect( to a different page );
    }
}

read我应该开启MARS,打开它,什么也没有。但我确实知道我不需要MARS因为我总是处理上下文并且我没有使用多个线程所以不知道为什么我会得到这个例外。

有什么想法吗?

这是堆栈跟踪

[InvalidOperationException: The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.]
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +4263799
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +53
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +16
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +39
System.Linq.Queryable.First(IQueryable`1 source, Expression`1 predicate) +83

0 个答案:

没有答案