首页 新闻 赞助 找找看

EntityFrameWork异常

0
悬赏园豆:20 [已解决问题] 解决于 2012-06-22 09:34
 1      /// <summary>
 2         /// Save entity'propertity which is not null
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="entity"></param>
 6         public void SetModifyColumnsWithOutNull<T>(T entity) where T : EntityObject
 7         {
 8             ObjectStateEntry stateEntry = null;
 9             bool isPresent = _ctx.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry);
10             if (stateEntry == null)
11                 _ctx.AttachTo(typeof(T).Name, entity);
12 }

错误:An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

说明:我是把上下文放在线程的CallContext里面了,在调用这个方法之前,我查询过该对象,修改之后,调用这个方法进行更新,结果报上述错误。

疑问:既然从上下文中获取不到对象状态,那附加对象为何还是出错呢?请大虾们赐教小弟

魂殇的主页 魂殇 | 初学一级 | 园豆:154
提问于:2012-06-21 15:54
< >
分享
最佳答案
0

/// <summary>
/// Save entity'propertity which is not null
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
public void SetModifyColumnsWithOutNull<T>(T entity) where T : EntityObject
{
ObjectStateEntry stateEntry = null;//对象状态
EntityKey key = _Context.CreateEntityKey(typeof(T).Name, entity);//构造对象Key,通过Key来检测上下文中是否存在对象
bool isPresent = _Context.ObjectStateManager.TryGetObjectStateEntry(key, out stateEntry);//检测是否存在对象
if (isPresent)//当返回值为true的时候,对象在上下文中已经存在
{
var oldEntity = (T)_Context.GetObjectByKey(key);//通过Key获取对象
var propertys = from p in entity.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)
where p.GetGetMethod(false) != null && p.GetValue(entity, null) != null
let attribute = (EdmScalarPropertyAttribute)Attribute.GetCustomAttribute(p, typeof(EdmScalarPropertyAttribute))
where attribute != null && !attribute.EntityKeyProperty
select p;//通过反射,获取需要保存的对象中值不为空的Property
foreach (var item in propertys)
{
item.SetValue(oldEntity, item.GetValue(entity, null), null);//通过反射,将需要保存的对象中不为空的Property赋值给上下文中的对象
}
}
else//如果上下文中不存在对象,则需要
{
_Context.AttachTo(typeof(T).Name, entity);
_Context.SetModifyColumnsWithOutNull(entity);
}
}

魂殇 | 初学一级 |园豆:154 | 2012-06-22 09:32
其他回答(2)
0

看错误信息的意思是EF上下文中已经有当前这个实体了,所以不需要AttachTo,你把AttachTo这一行去掉试试

收获园豆:10
artwl | 园豆:16736 (专家六级) | 2012-06-21 15:59

如果有的话,那我应该通过

bool isPresent = _ctx.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry);
能获取到这对象的状态,执行完这句,isPresent 是false,stateEntry是空对象
支持(0) 反对(0) 魂殇 | 园豆:154 (初学一级) | 2012-06-21 16:15
0

AttachTo 好像不对吧!

收获园豆:10
jerry-Tom | 园豆:4077 (老鸟四级) | 2012-06-21 16:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册