在 EF Core 中更新时导航属性未删除

问题描述 投票:0回答:1

我的数据库中有一个具有以下属性的实体

public class Employee : 
{
    public long Id { get; set; }
    public string EmployeeNumber { get; set; }

    [ForeignKey("EmployeesId")]
    public List<PrisonsLkpt> Prisons { get; set; }  

    // .....     
}

它还有其他属性,但它们并不那么重要。因此,当我添加一个包含 4 个监狱的新实体时,它与插入完美配合。但在更新时,如果我从列表中删除 2 个监狱,它不会从集合中删除这 2 个监狱。不过,如果我再添加一所监狱,它就会添加到收藏中。

c# .net linq entity-framework-core
1个回答
0
投票

这取决于您尝试删除相关实体的具体方式。例如,从员工身上移除特定监狱:

int[] prisonIdsToRemove = new { 1, 2 };

var employee = context.Employees
    .Include(x => x.Prisons)
    .Single(x => x.Id == employeeId);

var prisonsToRemove = employee.Prisons
    .Where(x => prisonIdsToRemove.Contains(x.Id));

foreach (var prison in prisonsToRemove)
    employee.Prisons.Remove(prison);

context.SaveChanges();

基本上急切加载监狱 /w

Include
,然后识别要删除的员工实例并将其从员工集合中删除。对于 EF,它使用实例跟踪来确定是否应添加、删除、关联或取消关联记录。您需要避免设置
employee.Prisons = new List<Prison>();
等“捷径”来清除监狱以重新关联新的一组监狱。这会擦除 EF 将用来了解该员工拥有哪些现有监狱的跟踪收集参考。还要确保您没有禁用 DbContext 上的跟踪或读取员工 /w
AsNoTracking()

© www.soinside.com 2019 - 2024. All rights reserved.