0

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.

enter image description here

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);
Kamil Folwarczny
  • 581
  • 1
  • 3
  • 13

3 Answers3

0

Do you you auto increment on your Id column ? Defined in your SQL database. If it is the case then try to decorate the corresponding property of your entity with DatabaseGenerated.Identity attribute.

Sébastien Krejci
  • 431
  • 1
  • 4
  • 9
0

I found the solution. I am using Code First approach for generating Data Object Model. EF created this relationship as:

    modelBuilder.Entity<Employee>()
        .HasRequired(s => s.Person)
        .WithRequiredPrincipal(ad => ad.Employee);

By EF definition Employee is main refereced class, which is wrong. I changed referenced class to Person and everything works fine so far.

Correct relationship:

    modelBuilder.Entity<Employee>()
        .HasRequired(s => s.Person)
        .WithRequiredDependent(ad => ad.Employee);

More about having referece and being reference in answer: Ef code first diference between principle and dependent

Kamil Folwarczny
  • 581
  • 1
  • 3
  • 13
0

I think you can solve your problem with SQL Server,make relationship with employee in your SQL server and try inserting new person again.

Roxana Sh
  • 294
  • 1
  • 3
  • 14