使用EF 6中的导航属性删除

时间:2014-12-02 07:09:24

标签: c# asp.net entity-framework-6

我在我的应用程序中使用EF 6数据库模式。我有一个表TBL_USER,在其他表中有1:N个关系。其中一个是TBL_USER_CASETBL_USER的主键在TBL_USER_CASE中充当外键。

现在我要从TBL_USER删除一些用户。在此之前,我需要删除TBL_USER_CASE中的相应条目。我正在使用以下代码

 private long DeleteUser(long UserID)
    {
        using(VerbaTrackEntities dataContext = new VerbaTrackEntities())
        {
            TBL_USER user = dataContext.TBL_USER.Where(x => x.LNG_USER_ID == UserID).SingleOrDefault();
            if(user != null)
            {
                foreach (var cases in user.TBL_USER_CASE.ToList())
                {
                    user.TBL_USER_CASE.Remove(cases);                          
                }
            }
            dataContext.SaveChanges();
        }
        return 0;
    }

这里我得到了异常

Additional information: 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

如何正确执行此操作?

2 个答案:

答案 0 :(得分:0)

好的,如果你的目标是删除用户,你可以让框架处理子关系。你可以试试这个:

private long DeleteUser(long UserID)
{
    using(VerbaTrackEntities dataContext = new VerbaTrackEntities())
    {
        TBL_USER user = dataContext.TBL_USER.
                                 SingleOrDefault(x => x.LNG_USER_ID == UserID);
        if(user != null)
        {       
            dataContext.TBL_USER.Remove(user); 
            dataContext.SaveChanges();
        }
    }
    return 0;
}

更新:你可以尝试一下这个:

private long DeleteUser(long UserID)
{
    using(VerbaTrackEntities dataContext = new VerbaTrackEntities())
    {
        TBL_USER user = dataContext.TBL_USER
                             .SingleOrDefault(x => x.LNG_USER_ID == UserID);
        if(user != null)
        {
            foreach (var cases in user.TBL_USER_CASE.ToList())
            {
                //little modification is here
                dataContext.TBL_USER_CASE.Remove(cases);                          
            }
        }
        dataContext.SaveChanges();
    }
    return 0;
}

答案 1 :(得分:0)

我通过阅读网络设法做到了这一点。

我这样做了
 System.Data.Entity.Core.Objects.ObjectContext oc = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)dataContext).ObjectContext;
 foreach(var Cases in user.TBL_USER_CASE.ToList())
    {                        
       oc.DeleteObject(Cases);                       
    }                    
    oc.SaveChanges();
    dataContext.TBL_USER.Remove(user);