c# - 如何避免 "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection"错误?

标签 c# asp.net entity-framework

我对 .NET 中的 Entity Framework 有疑问。

我有一个简单的 ASP .NET 网页,它必须使用此功能在 SQL Server 中插入一些数据:

public void InsertSimulation()
{
    icarus_portalEntities entitites = new icarus_portalEntities();

    // Build the Simulation
    T004_SIMULATIONS tSimulation = T004_SIMULATIONS.CreateT004_SIMULATIONS(0, name_, creationDate_, gsoapPort_, endTimeStep_, scenarioX_, scenarioY_, penetrationRates_.wifi, penetrationRates_.gprs, penetrationRates_.wimax, penetrationRates_.lte, penetrationRates_.mcn, penetrationRates_.edge, penetrationRates_.hsdpa, totalNumberOfNodes_, "RandomWalkMobility", ((RandomWalkMobility)mobility_).vehicularSpeed, ((RandomWalkMobility)mobility_).angleVariation, ((RandomWalkMobility)mobility_).cellRadius, ((RandomWalkMobility)mobility_).decorrelation, ((RandomWalkMobility)mobility_).minimumDistance, false);

    // Bind the Simulation with the FK of user
    T001_USERS tUser = entitites.T001_USERS.First(p => p.user_name == createdBy_);
    tUser.T004_SIMULATIONS.Add(tSimulation);

    // Bind the Simulation with the FK of the crmm
    T003_CRRM tCrmm = entitites.T003_CRRM.First(p => p.name == crmm_.Name);
    tCrmm.T004_SIMULATIONS.Add(tSimulation);

    // Add the created sessions to the simulation
    foreach (SimulationSession session in SimulationSession.createdSessions_)
    {
        if (session.GetType() == typeof(WebSession))
        {
            // Build the session and web session
            T008_SESSIONS tWebSession = ((WebSession)session).Insert(entitites);

            // Bind the session to the simulation
            tSimulation.T008_SESSIONS.Add(tWebSession);
        }
    }

    // Add the enanabled technologies to the simulator
    foreach (EnabledTechnologies enabled in enabledTechnologies_)
    {
        // Build the enabled technology
        T005_ENABLED_TECHNOLOGIES tEnabled = T005_ENABLED_TECHNOLOGIES.CreateT005_ENABLED_TECHNOLOGIES(0, enabled.centerX, enabled.centerY, enabled.radius, false);

        // Bind the enabled technolgy with the simulator
        T002_SIMULATORS tSimulator = entitites.T002_SIMULATORS.First(p => p.id == enabled.simulatorId);
        tSimulator.T005_ENABLED_TECHNOLOGIES.Add(tEnabled);

        // Bind the enabled technolgoy with the simulation
        tSimulation.T005_ENABLED_TECHNOLOGIES.Add(tEnabled);
    }

    entitites.SaveChanges();
}

问题是当代码尝试句子时:

// Bind the enabled technolgy with the simulator
T002_SIMULATORS tSimulator = entitites.T002_SIMULATORS.First(p => p.id == enabled.simulatorId);

它给我错误:

ObjectContext 实例已被释放,不能再用于需要连接的操作。

我发现,在其他相关问题中,实体对象 (entities) 的 connection 在传递给语句中的方法时以某种方式关闭:

// Build the session and web session
T008_SESSIONS tWebSession = ((WebSession)session).Insert(entitites);

Insert 函数实现为:

public T008_SESSIONS Insert(icarus_portalEntities entities)
{
    // Create new session object with data
    T008_SESSIONS tSession = T008_SESSIONS.CreateT008_SESSIONS(0, name_, periodicty_, false);
    using (entities)
    {
        // Create new web session object with data
        T010_SESSIONS_WEB tSessionWeb = T010_SESSIONS_WEB.CreateT010_SESSIONS_WEB(0, (int)lambda_, (int)pagesPerSession_, (int)objectsSize_.alpha, (int)objectsSize_.beta, (int)objectsPerWebPage_.alpha, (int)objectsPerWebPage_.beta, (int)timeBetweenPages_.alpha, (int)timeBetweenPages_.beta, (int)timeBetweenObjects_.alpha, (int)timeBetweenObjects_.beta, false);

        // Add to the session the web session (bind FK)
        tSession.T010_SESSIONS_WEB.Add(tSessionWeb);

        // Add session to the rest of the entities
        entities.AddToT008_SESSIONS(tSession);

        // Commit all the data to the database
        entities.SaveChanges();

        //var tempSession = entities.T008_SESSIONS.First(n => n.Equals(tSession.id));
        //tempSession.T010_SESSIONS_WEB.Add(tSessionWeb);
    }
    return tSession;        
}

好消息是Insert函数封装的代码我可以移动到调用的地方。所以我的问题是:如果有一个地方我会被迫调用函数怎么办?那我怎么能避免这个错误。传递参数作为引用(我试过了,没用)

非常感谢您!

朱伦。

最佳答案

What if there is a place in which I would be forced to call the function? How then I could avoid the error. Passing the parameter as reference (I tried and did not work)

问题出在您的 Insert() 函数中,您将 entities 包装在 using(){} 语句中。

using (entities) //calls dispose
{
} 

当使用完成时,它会调用您的实体并关闭您的连接。

您的上下文应该在我们工作单元的生命周期内保持活跃。理想情况下,您的 using 语句应该在 InsertSimulation() 中,因为从代码看来这是您的工作单元 entitites

关于c# - 如何避免 "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5485331/

相关文章:

asp.net - 无需刷新 token 即可获取 AdWords customerId

visual-studio-2010 - 具有 Table-per-Type 继承的 Entity Framework 模型

c# - Entity Framework 代码优先异常 "Duplicate entry ' 0' for key ' PRIMARY'"

c# - dotnet 不支持多重继承。但是多接口(interface)支持吗?

c# - 使用rabbitMQ发送和接收相同的消息

asp.net - 使用 Signalr 拥有一个类似 facebook 的通知系统

entity-framework - Entity Framework 5.0 Beta - 是否会提供 DbContext 代码生成模板?

c# - datagridview即使没有数据c#也可见网格线

c# - 使用 LINQ,我如何选择特定索引处的项目?

asp.net - 使用 GroupBy Id 选择 ASP NET CORE Entity Framework