Entity Framework Code first self referencing ID inserts wrong entity

ef-code-first entity-framework entity-framework-core

Question

I'm having trouble inserting into a table with code first using EF Core 2.0.

I get this exception when calling my context.SaveChanges()

Cannot insert explicit value for identity column in table 'Departments' when IDENTITY_INSERT is set to OFF.

Here is my Model:

public class Department 
{
  public int ID { get; set; }
  public string Name { get; set; }
  public int? ParentDepartmentID { get; set; }
  public Department ParentDepartment { get; set; }
}

When I use the SQL Server Profiler I can see that the insert statement of an object which looks like this: Object im trying to save

Is clearly trying to insert my ParentDepartment again.

exec sp_executesql N'SET NOCOUNT ON;
INSERT INTO [Departments] ([ID], [Name], [ParentDepartmentID])
VALUES (@p0, @p1, @p2);
',N'@p0 int,@p1 nvarchar(4000),@p2 int',@p0=1,@p1=N'Aalborg',@p2=NULL

My save function which saves the object shown above looks like this:

public string Save()
{
  string result = this.Validate();

  if (result.Equals(""))
  {
    using (LinerContext context = new LinerContext())
    {
      context.Departments.Add(this);
      context.SaveChanges();
    }
  }
  return result;
}

Really hope someone can help - thanks in advance!

1
2
5/1/2018 10:22:51 PM

Accepted Answer

Fixed; I just needed to attach the parentdepartment to the dbset

0
7/30/2018 7:45:34 AM

Popular Answer

What you need is probably to change the way you have set your model. For self referencing you should probably do something like this (can refer to this answer for a Fluent API implementation on the model creation too):

public class Department 
{
    public int ID { get;set; }
    public string Name { get;set; }
    public int? ParentDeparmentId { get; set; }

    [ForeignKey("ParentDeparmentId ")]
    public Department ParentDeparment { get; set; }
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow