2013-04-13 213 views
1

在我的数据库模型中,我有4个实体:Order,Service,Client,Employee。 他们的关系:删除实体框架中的孩子

客户0..1 - *订购

订购1 - *服务

员工1 - *服务。

我试图删除特定的顺序所有服务,但我得到一个InvalidOperationException: 操作失败:关系不能被改变,因为一个或多个外键的属性是不可为空。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新的关系,必须为外键属性指定另一个非空值,或者必须删除不相关的对象。

这里是我的代码:

 public static void ClearSevicesInOrder(int orderId) 
     { 
      using (DbEntities context = new DbEntities()) 
      { 
       var o = context.Orders.Find(orderId); 
       o.Services.Clear(); 
       context.SaveChanges(); 
      } 
     } 

我该怎么办错了吗?

回答

0

我做了一篇关于此的博客文章,并提供了一个可能的解决方案。 http://wimpool.nl/blog/DotNet/extending-entity-framework-4-with-parentvalidator

简而言之:既要工作,你必须在服务列表中

+1

感谢事先删除每一个服务! 我的代码: foreach(var item in context.Services.Where(s => s.OrderID == orderId)) { context.Services.Remove(item); } context.SaveChanges(); –