繁体   English   中英

在 EF 6 中更新父实体时如何删除子实体?

[英]How to delete child entities when updating a parent entity in EF 6?

这是我的实体:

public class Question
{
    public int Id { get; set; }
    public string Text { get; set; } = string.Empty;
    public ICollection<Answer> Answers { get; set; } = new List<Answer>();
    public TimeSpan TimeForAnswer { get; set; }
    public int TestId { get; set; }
}
public class Answer
{
    public int Id { get; set; }
    public string Text { get; set; } = string.Empty;
    public int QuestionId { get; set; }
    public int Points { get; set; }
}

如果我只更新我的父实体:

public void Update(Question entity)
{
    _dbContext.Questions.Update(entity);
}

EF 将添加/更新子实体,但如果有任何缺失则不会删除。 我搜索了一下,找到了这篇文章 并像这样修改了我的方法:

public void Update(Question entity)
{
    var existingParent = _db.Questions
        .Include(p => p.Answers)
        .SingleOrDefault(p => p.Id == entity.Id);
        
    if (existingParent != null)
    {
        existingParent.Answers.Clear();
    }

    _db.Questions.Update(entity);
}

现在我收到这个错误:

System.InvalidOperationException: The instance of entity type 'Question' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

如何解决这个问题?

调用:

_db.Questions.Update(entity);

尝试开始跟踪实体,但它已被查询跟踪:

var existingParent = _db.Questions
    .Include(p => p.Answers)
    .SingleOrDefault(p => p.Id == entity.Id);

我会 go 为:

public void Update(Question entity)
{
    var existingParent = _db.Questions
        .Include(p => p.Answers)
        .SingleOrDefault(p => p.Id == entity.Id);
        
    if (existingParent != null)
    {
        // Update Parent Entity Properties
        existingParent.Text = entity.Text;
        existingParent.TimeForAnswer = entity.TimeForAnswer;
        existingParent.TestId = entity.TestId;
        // remove existing from tracked Question
        existingParent.Answers.Clear();
        // add answers from Question in method param
        existingParent.Answers.AddRange(entity.Answers);
    }
    else
    {
        // Add the question with answers to the db
        _db.Questions.Add(entity);
    }
}

暂无
暂无

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

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