0

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.

Anton
  • 33
  • 4
  • I'd just create a link table so that it isn't a many-many – Andrew Corrigan Apr 29 '22 at 09:08
  • Link table is already automatically created, as you see in error, problem is in adding links to the table 'CompetencyExecutor' – Anton Apr 29 '22 at 09:24
  • Ohh, OK, I'd misread that bit - I didn't know it could automatically create a link table (I tend to reverse engineer from the SQL, not use EF to build the database). In that case, it looks like you're trying save the link, before saving the `Competency`. – Andrew Corrigan Apr 29 '22 at 12:57

1 Answers1

0

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.

Anton
  • 33
  • 4