首页 文章

如何避免“已经处理了ObjectContext实例,不能再用于需要连接的操作”错误?

提问于
浏览
4

我对.NET中的实体框架有疑问 .

我有一个简单的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);

它给了我错误:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

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

// 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)

非常感谢你提前!

Julen .

2 回答

  • 10

    如果有一个地方我将被迫调用该功能怎么办?那么我怎么能避免错误 . 传递参数作为参考(我尝试过但没有工作)

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

    using (entities) //calls dispose
    {
    }
    

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

    您的上下文应在我们工作单元的整个生命周期内保持活动状态 . 理想情况下, using 语句应该在 InsertSimulation() 中,因为它出现的代码是您的工作单元 entitites .

  • 2

    如果你看一下方法public T008_SESSIONS Insert(icarus_portalEntities entity)

    您正在传递您的实体对象的引用,因为它正在使用using语句

    using (entities) {}
    

    它将处置该对象

相关问题