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里面了,在调用这个方法之前,我查询过该对象,修改之后,调用这个方法进行更新,结果报上述错误。
疑问:既然从上下文中获取不到对象状态,那附加对象为何还是出错呢?请大虾们赐教小弟
/// <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);
}
}
看错误信息的意思是EF上下文中已经有当前这个实体了,所以不需要AttachTo,你把AttachTo这一行去掉试试
如果有的话,那我应该通过
bool isPresent = _ctx.ObjectStateManager.TryGetObjectStateEntry(entity, out stateEntry);
能获取到这对象的状态,执行完这句,isPresent 是false,stateEntry是空对象
AttachTo 好像不对吧!