2

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!

Matt Baech
  • 404
  • 11
  • 23

2 Answers2

0

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; }
}
Anastasios Selmani
  • 3,579
  • 3
  • 32
  • 48
  • I have tried that to no avail, exact same scenario. I cannot count the times I have dropped my DB and recreated with other migrations all different flavors of DataAnnotations and fluent API – Matt Baech May 02 '18 at 09:40
0

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

Matt Baech
  • 404
  • 11
  • 23