Reputation: 93
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();
}
}
}
Upvotes: 0
Views: 1810
Reputation: 3756
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:
Upvotes: 1