您的位置:首页 > 其它

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

2013-10-17 03:33 288 查看
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 中去执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: