SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Users_Companies_CompanyId"

c# entity-framework-core sql-server

Question

I want to add a new user in my database but take the exception. Unfortunately I'm new to both SQL Server and EF, but searching for the answer made me understand that the problem is somewhere in the SQL Server tables and impossibility of connection user and company there. Should I do something with Id or CompanyId or what?

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Users_Companies_CompanyId". The conflict occurred in database "companiesdb", table "dbo.Companies", column 'Id'. The statement has been terminated.

Code:

public class User
{
        public string Name { get; set; }
        public int Age { get; set; }
        public int CompanyId { get; set; } // for what???
        public Company Company { get; set; }
        public int Id { get; set; } //for what?
}

public class Company
{
        public int Id { get; set; } //for what?
        public string Name { get; set; }
        public List<User> Users { get; set; }

        public Company()
        {
            Users = new List<User>();
        }
}

using Microsoft.EntityFrameworkCore;

namespace DataApp1.Models
{
    public class UserDb : DbContext
    {
        public DbSet<User> Users { get; set; } //create db for users
        public DbSet<Company> Companies { get; set; } //and for companies they belong
        public UserDb(DbContextOptions<UserDb> options)
            : base(options)
        {
            Database.EnsureCreated();
        }
    }
}
1
0
4/1/2019 8:01:14 PM

Popular Answer

Your User class, which apparently relates to your Users table, has a field for CompanyId. Based on the error, your database requires a correct company ID to be added to the DB every time.

If you have not added the company to the Companies table before adding a User, the insert will fail with this error. If you insert the User with no value in the CompanyId field, this error will occur.

So, your correct program flow would be:

  • Add Company to Companies if it doesn't exist there
  • Get the correct CompanyId
  • Add the CompanyId to the CompanyId field in the User record before saving it.
1
4/1/2019 8:07:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow