我得到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; }
...
}
我试图从数据库获取再次requestComment
,将其标记为Deleted
和Save
,但这并不能帮助。
var dbComment = RequestCommentRepository.FindFirstOrDefault(x => x.User.Id == localId
&& x.RequestId == originalRequest.Id);
RequestCommentRepository.Context.Entry(dbComment).State = EntityState.Deleted;
RequestCommentRepository.SaveChanges();
更改'public int RequestId {get;组; }'到'公众诠释? RequestId {get;组; }'。还要将删除行为设置为“级联”,以便EF将删除其他表中的相关条目。 – aff
@flechilla,谢谢你的评论。但是有没有其他解决方案不需要更改实体? – demo
您是否尝试将上下文中的删除行为更改为Cascade。 EF应该为你照顾。如果不是,你应该首先删除你在其他表中删除的相关行。 – aff