There are these two entities:
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public CompanyVehicle CompanyVehicle { get; set; }
}
and
public class CompanyVehicle
{
public int Id { get; set; }
public string Name { get; set; }
public Employee Employee { get; set; }
}
Using Entity Framework Core 5.0.8
on SQL Server 2019
, the configuration for CompanyVehicle is:
entityBuilder.HasOne(t => t.Employee)
.WithOne(t => t.CompanyVehicle)
.HasForeignKey<Employee>(t => t.Id)
.IsRequired();
And we'll try to insert something:
public void Create(Employee employee)
{
employee.CompanyVehicle = new CompanyVehicle();
dbContext.Add<Employee>(employee);
dbContext.SaveChanges();
}
The above code used to work fine in EF6
. Two new records in both Employee and CompanyVehicle tables were created with the same Id
. After migrating to EF Core 5.0.8
, dbContext.SaveChanges() throws an exception:
System.InvalidOperationException: 'The value of 'Employee.Id' 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.'
Note that these entities are just examples and the database design should not be altered in my case.
Update
After some more investigation, I've found out my problem is:
Having X
(principal) and Y
(dependent) as two tables where X.Id
is PK for X
and Y.Id
is PK for Y
and also FK to X
, in EF Core a record of X
cannot be inserted.
IDENTITY(1,1)
I don't know why... – Annunciata