EntityFramework. 如何根据判断ObjectStateEntry,来决定是否Attach Entity

hoken2020856 2011-09-05 12:02:09
新人深夜求教:
我的一个删除函数是这么写的:

public bool Delete(Sample et)
{
bool rv = true;
try
{//...
ObjectStateEntry oses = null;
bool isfound =((IObjectContextAdapter)_dataContext).ObjectContext.ObjectStateManager.TryGetObjectStateEntry(et, out oses);
if (oses==null)
_dataContext.Samples.Attach(et);
_dataContext.Samples.Remove(et);
_dataContext.Commit();
}
}
catch(Exception e)
{
rv = false;
}
return rv;
}

一开始没有加ObjectStateEntry 的逻辑,发现有的时候无法删除,报错:An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
显然一个Entity不能Attach两次。于是在MSDN上发现了判断ObjectStateEntry的方法,就加上了。但是现在TryGetObjectStateEntry方法似乎总是失败的。
我曾经干脆就不Attach()了,相同的数据debug下来,居然又报这样的错:The object cannot be deleted because it was not found in the ObjectStateManager.
现在情况就是Attach,然后remove,说不能重复Attach;如果不Attach,直接Remove,又说我忘了Attach...
这可怎么办呢?
...全文
308 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
LMAOhuaNL 2011-09-05
  • 打赏
  • 举报
回复
真杯具了,关注
hoken2020856 2011-09-05
  • 打赏
  • 举报
回复
现在不是try的问题。是我的Entity没法强制转换。
[Quote=引用 5 楼 dongxinxi 的回复:]
外面不需要try的

C# code

ObjectStateManager objectStateManager = context.ObjectStateManager;
ObjectStateEntry oses = null;
bool found = _dataContext.ObjectStateManager.TryGetObjectStateEntry(((IEntit……
[/Quote]
  • 打赏
  • 举报
回复
外面不需要try的
ObjectStateManager objectStateManager = context.ObjectStateManager;
ObjectStateEntry oses = null;
bool found = _dataContext.ObjectStateManager.TryGetObjectStateEntry(((IEntityWithKey)et).EntityKey, out oses);
if(!found) //从逻辑上讲应该判断这个标识
_dataContext.Samples.Attach(et);
。。。
hoken2020856 2011-09-05
  • 打赏
  • 举报
回复
谢谢2楼,你说的没错。可是你的方法不好使啊:
Unable to cast object of type 'System.Data.Entity.DynamicProxies.Sample_7AA525D6CFF44D3231CDF1FF262C2C21B315D283DE56DF13BF7B932669AE491C' to type 'System.Data.Objects.DataClasses.IEntityWithKey'.

[Quote=引用 2 楼 abbey 的回复:]
你的参数et是个Sample类的Entity对象吧,对应于表Samples中的行吧。

那么你试试把TryGetObjectStateEntry的第一个参数进行适当的转换,象下面这样,然后看TryGetObjectStateEntry()调用是否成功。
TryGetObjectStateEntry(((IEntityWithKey)et).EntityKey, out oses);


……
[/Quote]
hoken2020856 2011-09-05
  • 打赏
  • 举报
回复
想了一个笨方法回避了这个问题。这可能是由于不同的_dataContext操纵相同的数据导致的。反正很奇怪。而且来自System.Data.Entity的DBSet,在检查ObjectStateEntry时根本不用强制类型转换就能正确获得ObjectState,转换也转换不过去。可是我的那种情况检查ObjectStateEntry时总是失败。也不知为什么。
贪玩的老鼠 2011-09-05
  • 打赏
  • 举报
回复
没用过,帮你顶一下
老毕 2011-09-05
  • 打赏
  • 举报
回复
你的参数et是个Sample类的Entity对象吧,对应于表Samples中的行吧。

那么你试试把TryGetObjectStateEntry的第一个参数进行适当的转换,象下面这样,然后看TryGetObjectStateEntry()调用是否成功。
TryGetObjectStateEntry(((IEntityWithKey)et).EntityKey, out oses);




110,501

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧