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:
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!
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; }
}