实体框架MappingException:类型'XXX已被映射一次以上 [英] Entity framework MappingException: The type 'XXX has been mapped more than once

查看:165
本文介绍了实体框架MappingException:类型'XXX已被映射一次以上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用实体框架的Web应用程序。

I'm using Entity framework in web application. ObjectContext is created per request (using HttpContext), hereby code:

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;



不是每一次,但有时我有这样的例外:

Not every time, but sometimes I have this exception:

System.Data.MappingException是由用户代码消息未处理=的
型XXX已经被映射不止一次。来源= System.Data.Entity的

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

我绝对困惑,我没有什么可导致此问题的任何想法。

I'm absolutely confused and I don't have any idea what can caused this problem.

任何人可以帮助我吗?

推荐答案

它看起来像一个同步问题。一个简单的解决办法是有一个共享锁对象(类中):

It looks like a synchronisation problem. A simple solution would be to have a shared lock object (within your class):

private static object _lock = new object();



你的代码变成:

Then your code 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 basically means that once a thread enters the "lock" block, no other threads can access that block until the first thread finishes. This will stop the contention between the "Contains" method and the "Add" method.

注意:
。如果其他的任何地方您应用程序正在访问的HttpContext.Current项目集合,您将需要同步那里。这是明智的创建自定义集合,它添加到项目集合,并同步上网本。

Note: If anywhere else in you application is accessing the Items collection in HttpContext.Current, you will need to synchronise there as well. It is wise to create a custom collection, add this to the Items collection, and synchronise the access to this.

这篇关于实体框架MappingException:类型'XXX已被映射一次以上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆