尝试保存更改时,错误对象 ID 未知。将多对多添加到数据库

Error Object Id' is unknown when attempting to save changes. Adding Many to Many to the DB

我有具有多对多关系的对象。

public class Executor
{
    public long Id { get; set; }

    public string Name { get; set; }

    public List<Competency> Competency { get; set; }

}

public class Competency
{      

    public long Id { get; set; }

    public string CompetencyName { get; set; }

    public List<Executor> Executor { get; set; }
}

我正在使用 EF Core 5PostgreSQL DB。我不能只向数据库添加新的执行者,首先我需要在数据库中找到所有能力,因为这个problem

所以,我现在的代码是这样的:

public async Task<ServiceResponse<ExecutorDto>> AddExecutor(ExecutorDto newExecutor, long userId)
    {
        var serviceResponse = new ServiceResponse<ExecutorDto>();
        try
        {
            var executor = _mapper.Map<Executor>(newExecutor);
            executor.Competency.Clear();
            executor.Competency = _context.Competencies.Where(i => newExecutor.Competency.Contains(i)).ToList();

            _context.Executors.Add(executor);                
            await _context.SaveChangesAsync();

            ...

但是在保存的时候我有错误。

The value of 'CompetencyExecutor (Dictionary<string, object>).CompetencyId' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known.

我试图通过多种方式解决这个问题,但找不到解决方案。

好吧,这很愚蠢,问题是因为 List 中的 Competency 之一有 Id=0。 PostreSQL 将 0 识别为 NULL。只需将 Id 更改为 1 或其他正数即可。