解决EF一对一或多对一的删除

people 类中有 zhengshu类 且是一对一,现在要删除people类中的zhengshu

网上看了N多办法,什么更新外键什么滴。

其实方法简单极了

using (KJExamEntity context = new KJExamEntity())
{
context.Peoples.Attach(people);
context.ZhengShus.Remove(people.SBZhengShu);
context.SaveChanges();
}

完事之后people.SBZhengShu的会自动为null。

万万不可

using (KJExamEntity context = new KJExamEntity())
{
context.Peoples.Attach(people);
people.SBZhengShu=null;
context.SaveChanges();
}

using (KJExamEntity context = new KJExamEntity())
{
context.ZhengShus.Attach(zs);
people.SBZhengShu=null;
context.SaveChanges();
}

总之一句话 从爹删起,微软的想法很简单,你要删儿子,爹肯定受影响 所以你要把爹和儿子放在一个context 中去执行。

posted @ 2013-10-17 03:33  为森  阅读(628)  评论(0编辑  收藏  举报