Entity framework MappingException: 'XXX' has been mapped several times.

.net c# entity-framework

Question

In my web application, Entity Framework is used. The following code creates an object context for each request (using the http context).

string ocKey = "ocm_" + HttpContext.Current.GetHashCode().ToString();
if (!HttpContext.Current.Items.Contains(ocKey))
{
    HttpContext.Current.Items.Add(ocKey, new ElevationEntityModel(EFConnectionString));
}
_eem = HttpContext.Current.Items[ocKey] as ElevationEntityModel;

I don't have this exception every time, but sometimes I do:

System.Data.MappingException was unhandled by user code Message=The type 'XXX' has been mapped more than once. Source=System.Data.Entity

I'm really perplexed, and I have no clue what may have caused this issue.

Can somebody assist me?

1
26
10/9/2012 4:51:29 PM

Accepted Answer

It seems to be a synchronization issue. Having a shared lock object (inside your class) is an easy fix.

private static object _lock = new object();

Your code then becomes:

string ocKey = "ocm_" + HttpContext.Current.GetHashCode().ToString(); 

lock (_lock) {
    if (!HttpContext.Current.Items.Contains(ocKey)) 
    { 
          HttpContext.Current.Items.Add(ocKey, new ElevationEntityModel(EFConnectionString)); 
    } 
    _eem = HttpContext.Current.Items[ocKey] as ElevationEntityModel; 

}

The lock block essentially indicates that until the first thread completes, no other threads may access that block after it has entered the "lock" block. The conflict between the "Contains" method and the "Add" method will be resolved as a result.

Note: You must synchronize anywhere in your application that the Items collection in HttpContext.Current is used. A custom collection should be created, added to the Items collection, and its access should be synchronized.

19
2/1/2012 8:29:49 AM

Popular Answer

This occurs when many threads are active and you access the same ObjectContext without first synchronizing the threads.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow