Search code examples
asp.net-mvcasp.net-mvc-3entity-frameworkentity-framework-4httpcontext

MVC 3 Entity Framework Error - Item has already been added. Key in dictionary


I am making a MVC 3 web application using Entity Framework but I am getting this error. In my data layer I used a class connection helper.

Error is followig:

Item has already been added. Key in dictionary: 'DbActiveContext' Key being added: 'DbActiveContext'

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: Item has already been added. Key in dictionary: 'DbActiveContext' Key being added: 'DbActiveContext'

Error is on Line 24:

Line 22:                 {
Line 23:                     _connection = new flashEntities(ConnectionString);
**Line 24:                     HttpContext.Current.Items.Add("DbActiveContext", _connection);**
Line 25:                 }
Line 26:                 return _connection;

my Connection helper class is as follow (Same connection helper class is working fine in another mvc 3 web application):

public ObjectContext Connection
    {
        get
        {
            if (_connection == null && HttpContext.Current.Items["DbActiveContext"] != null)
            {
                _connection = (flashEntities)HttpContext.Current.Items["DbActiveContext"];
            }
            else
            {
                _connection = new flashEntities(ConnectionString);
                HttpContext.Current.Items.Add("DbActiveContext", _connection);
            }
            return _connection;
        }
    }
    private ObjectContext _connection;

    public string ConnectionString
    {
        get
        {
            return ConfigurationManager.ConnectionStrings["flashEntities"].ToString();
        }
    }

Any help would be highly appreciable. Thanks


Solution

  • Something is causing the line

     HttpContext.Current.Items.Add("DbActiveContext", _connection);  
    

    to execute more than once. Take another look at your If condition. could you be causing it to fail more than once ? Say if _Connection was being set to null ...