'Error Object Id' is unknown when attempting to save changes. Adding Many to Many to the DB
I have objects with many to many relationship.
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; }
}
I am using EF Core 5 and PostgreSQL DB. I can`t just add new Executor to DB, first I need to find all competencies in the DB because of this problem.
So, my code now is like this:
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();
...
But on the Save moment I have error.
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.
I was trying to resolve this in many ways, but I can`t find the solution.
Solution 1:[1]
Well, it was stupid, the problem was because one of the Competency
in the List
has Id=0
. PostreSQL recognises 0 as NULL. Just need to change Id to 1 or another positive number.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anton |