繁体   English   中英

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

[英]Delete using navigation properties in EF 6

我在应用程序中使用EF 6数据库模态。 我有一个表TBL_USER在其他一些表中具有1:N关系。 其中之一是TBL_USER_CASE其中主键TBL_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

我如何正确执行此操作?

好的,如果您的目标是删除用户,则可以让框架处理子关系。 您可以尝试以下方法:

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;
}

我自己通过浏览网络做到了这一点。 我已经做到了

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM