尽管配置正确,但实体框架5 Cascade删除不起作用

时间:2013-03-01 04:40:56

标签: c#-4.0 entity-framework-5

我在父母>子关系中有两个表。

尝试删除父级时,我收到以下错误:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

我在dbfirst类型模型中使用SQL Server 2012。

在数据库中,删除规则设置为级联,我仔细检查.edmx中的规则也设置为级联。

我正在使用多个事务,然后在最后调用.SaveChanges()...不确定是否与它有任何关系。具体来说,我首先在另一个表上发布更新,然后删除。

以下是我的常见存储库代码:

public virtual ActionConfirmation<int> Delete(TRepository entity, bool boolCommitChgs = true)
        {

            try
            {   
                //DbSet.Remove(entity);
                _dataContext.Entry(entity).State = System.Data.EntityState.Deleted;
                if (boolCommitChgs)
                {
                    _dataContext.SaveChanges();
                }

                return CRUDMessage(true, "deleted", entity);
            }
            catch (Exception ex)
            {
                return CRUDMessage(false, "delete", entity, ex);
            }
        }

然后我完成事务并在这里调用SaveChanges,这是抛出错误的时间:

try
        {
            dbContext.SaveChanges();
            result = ActionConfirmation<int>.CreateSuccessConfirmation(
                            string.Format("{0} {1}: {2} successful.",
                            strNoun,
                            id, 
                            strVerb
                        ),
                            id
                        );
        }
        catch (Exception ex)
        {
          ....etc....

为什么我会收到此错误?

enter image description here enter image description here

1 个答案:

答案 0 :(得分:0)

问题可能是由于您的更新改变了一些关系。