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

时间:2011-03-30 10:50:50

标签: c# asp.net entity-framework

我怀疑.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);

它给了我错误:

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

我发现,在其他相关问题中,实体对象(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函数封装的代码我可以将它移动到被调用的地方。所以我的问题是:如果有一个地方我将被迫调用该功能怎么办?那么我怎么能避免错误。传递参数作为参考(我尝试过但不起作用)

非常感谢你!

Julen。

2 个答案:

答案 0 :(得分:10)

  

如果有一个地方我会被迫打电话给   功能?然后我怎么能避免   错误。将参数传递为   参考(我尝试过但没有用)

问题出在Insert()函数中,您在entities语句中包裹using(){}

using (entities) //calls dispose
{
} 

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

您的上下文应在我们工作单元的整个生命周期内保持活动状态。理想情况下,using语句应位于InsertSimulation(),而不是显示的代码,即您entitites的工作单元。

答案 1 :(得分:2)

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

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

using (entities) {}

它将处置对象