C# 实体框架映射异常:类型';XXX已映射多次
我在web应用程序中使用实体框架。ObjectContext是根据请求创建的(使用HttpContext),代码如下:C# 实体框架映射异常:类型';XXX已映射多次,c#,.net,entity-framework,C#,.net,Entity Framework,我在web应用程序中使用实体框架。ObjectContext是根据请求创建的(使用HttpContext),代码如下: string ocKey = "ocm_" + HttpContext.Current.GetHashCode().ToString(); if (!HttpContext.Current.Items.Contains(ocKey)) { HttpContext.Current.Items.Add(ocKey, new ElevationEntityModel(EFCo
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;
不是每次,但有时我有一个例外:
System.Data.MappingException未被用户代码消息处理=
类型“XXX”已映射多次。Source=System.Data.Entity
我完全糊涂了,我不知道是什么导致了这个问题
有人能帮我吗?这是由于正在进行多线程处理,并且在访问同一ObjectContext时没有先同步线程造成的…这看起来像是同步问题。一个简单的解决方案是(在类中)有一个共享锁对象: 然后您的代码变成:
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;
}
锁块基本上意味着一旦一个线程进入“锁”块,在第一个线程完成之前,没有其他线程可以访问该块。这将停止“Contains”方法和“Add”方法之间的争用
注意:
如果应用程序中的任何其他地方正在访问HttpContext.Current中的Items集合,您也需要在那里进行同步。明智的做法是创建一个自定义集合,将其添加到Items集合中,并同步对此的访问。我正在修复旧的、写得不好的Silverlight项目。这是RIA服务偶尔出现的问题之一。现在,我正试图用锁来防止它。
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;
}