I am trying to write into a table which has primary key from two parts. One of them is foreign primary key from another table. I am able to create this table, but not insert into.
I am using Entity Framework 6.4.0
My db is created by this code:
class School
{
public int Id { get; set; }
public string Name { get; set; }
public List<Classroom> Classrooms { get; set; }
}
class Classroom
{
[Key]
[Column(Order = 0)]
public int Id { get; set; }
[Key]
[Column(Order = 1)]
[ForeignKey("School")]
public int SchoolId { get; set; }
public School School { get; set; }
public string Name { get; set; }
}
class TestDbContext : DbContext
{
public DbSet<School> Schools { get; set; }
public DbSet<Classroom> Classrooms { get; set; }
}
How can I insert data into the Classrooms
table? I tried this (school with name: schoolName
is in db):
var context = new TestDbContext();`
var school = context.Schools.FirstOrDefault(s => s.Name == "SchoolName");
context.Classrooms.Add(new Classroom() {Name = "5B", School = school});
context.SaveChanges();
Result of this code was this error:
Cannot insert explicit value for identity column in table 'Classrooms' when IDENTITY_INSERT is set to OFF.