I have two tables, Person and Employee and i have newly created 1 .. 0,1
relationship between them respectively. PersonId in Person table had defined identity 1. EmployeeId in Employee table doesnt have identity defined.
When i insert new row into Person table with SQL Studio everything works fine, however when i try to insert data with Entity Framework i get error:
Cannot insert explicit value for identity column in table 'Person' when IDENTITY_INSERT is set to OFF.
PersonId is not explicitly defined and is 0
in time of saving.
Note that inserting new person row is working fine without relationship with employee.
Am I missing something obvious or my approach is completly wrong? Googling sadly didnt helped at all.
EDIT: I have found solution, but i will add entity code for people facing same problem.
Person entity:
public partial class Person
{
public Person()
{
}
[Key]
public int PersonId { get; set; }
...
public virtual Employee Employee { get; set; }
Employee Entity:
public partial class Employee
{
public Employee()
{
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int EmployeeId { get; set; }
...
public Data.Dal.Person Person { get; set; }
Relationship defined in context:
modelBuilder.Entity<Employee>()
.HasRequired(s => s.Person)
.WithRequiredPrincipal(ad => ad.Employee);