Mic*_*hal 26 .net c# entity-framework
我在Web应用程序中使用Entity框架.每个请求创建ObjectContext(使用HttpContext),特此代码:
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;
Run Code Online (Sandbox Code Playgroud)
不是每次都有,但有时我有这个例外:
用户代码未处理System.Data.MappingException消息=类型"XXX"已被多次映射.来源= System.Data.Entity的
我完全糊涂了,我不知道是什么导致了这个问题.
有谁能够帮我?
Dav*_*001 19
它看起来像一个同步问题.一个简单的解决方案是拥有一个共享锁对象(在您的类中):
private static object _lock = new object();
Run Code Online (Sandbox Code Playgroud)
然后你的代码变成:
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;
}
Run Code Online (Sandbox Code Playgroud)
锁定块基本上意味着一旦线程进入"锁定"块,在第一个线程完成之前,没有其他线程可以访问该块.这将停止"Contains"方法和"Add"方法之间的争用.
注意: 如果您的应用程序中的任何其他位置正在访问HttpContext.Current中的Items集合,那么您还需要同步它.创建自定义集合,将其添加到Items集合并同步对此集合的访问是明智的.
归档时间: |
|
查看次数: |
9660 次 |
最近记录: |