从具有一对多关系的实体中删除对象

时间:2016-05-10 14:13:53

标签: c# entity-framework foreign-keys one-to-many

我通过Id从request

获取Request originalRequest = RequestRepository.GetById(id);

然后我从请求评论中获取用户ID:

var origRecipientsIds = originalRequest.Comments.Select(c => c.User.Id).ToList();

从输入模型我收到新用户(ids)

 var editedRecipientsIds = model.Recipients.ToList();

然后按用户ID删除评论:

var recipientsIdToRemove = origRecipientsIds.Where(x => !editedRecipientsIds.Contains(x));
var recipientsToRemove = GetRecipientsToRemove(originalRequest, recipientsIdToRemove);
recipientsToRemove.ToList().ForEach(x => originalRequest.Comments.Remove(x));

GetRecipientsToRemove方法返回RequestComment

集合
private IEnumerable<RequestComment> GetRecipientsToRemove(Request originalRequest,
            IEnumerable<int> recipientsIdsToRemove)
        {
            var recipientsToRemove = new List<RequestComment>();
            foreach (var id in recipientsIdsToRemove)
            {
                int localId = id;
                var origComment = originalRequest.Comments.FirstOrDefault(x => x.User.Id == localId);
                if (!recipientsToRemove.Contains(origComment))
                {
                    recipientsToRemove.Add(origComment);
                }
            }
            return recipientsToRemove;
        }

毕竟我打电话给SaveChanges方法

RequestRepository.Context.Entry(originalRequest).State = EntityState.Modified;
            RequestRepository.SaveChanges();

并获取错误

  

由于一个或多个外键属性不可为空,因此无法更改关系。当对关系进行更改时,相关的外键属性将设置为空值。如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象。

实体RequestComment具有不可为空的FK到Request

public class RequestComment : IIdent
    {
        [ForeignKey("Request")]
        public int RequestId { get; set; }
        ...
    }

我尝试再次从db获取requestComment,将其标记为DeletedSave,但这没有用。

var dbComment = RequestCommentRepository.FindFirstOrDefault(x => x.User.Id == localId
                                                                           && x.RequestId == originalRequest.Id);
RequestCommentRepository.Context.Entry(dbComment ).State = EntityState.Deleted;
RequestCommentRepository.SaveChanges();

1 个答案:

答案 0 :(得分:0)

在您的后备DBMS中的实体之间似乎存在您在删除收件人实体之前未解决的外键关系。它可能位于评论实例和收件人实例之间。

确保您了解数据库的依赖关系。首先删除独立实例。