I'm having a problem with inserting a parent and child as part of a single SaveChanges().
Below are my two tables:
Company {
public int Id { get; set; }
public string Name { get; set; }
public virtual Collection<User> Users { get; } = new List<User>();
}
User {
public int Id { get; set; }
public string FirstName { get; set; } = null!;
public string LastName { get; set; } = null!;
public string? Email { get; set; }
public int CompanyId { get; set; }
public virtual Company Company { get; set; } = null!
}
I'm using FluentApi to map the relationship:
builder.Entity<User>(entity =>
{
entity.ToTable("users", "dbo");
entity.HasOne(d => d.Company).WithMany(p => p.Users).HasForeignKey(d => d.CompanyId);
});
The code I used is:
var company = new Company()
{
Name = "ABC"
}
_dbContext.Add(company);
var user = new User()
{
FirstName = "John",
LastName = "Smith",
Email = "John.smith@gmail.com"
}
company.Users.Add(user);
_dbContext.Add(user);
_dbContext.SaveChanges();
When I call SaveChanges() I get an error:
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Users_Companies_CompanyId". The conflict occurred in database "EFCore_Demo", table "dbo.Companies", column "Id".
The SQL being generated in the Output console is:
INSERT INTO dbo.Companies (Name)
OUTPUT INSERTED.Id
VALUES (@p0)
INSERT INTO dbo.Users (CompanyId, Email, FirstName, LastName)
OUTPUT INSERTED.Id
VALUES (@p1, @p2, @p3, @p4)
Thank you in advance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.