I've seen several posts about this particular issue, but I've been unable to resolve my issue from any of them.
I have 3 DB tables (rlinq uses Database First Model): Security (parent), Person (child), and Student (child).
* Security has a 1 to 0..1 relationship to Person.
* Security has a 1 to 0..1 relationship to Student.
* Each table has a ScEcotID column (PK on Security and Student; Person has it's own PK, but also has the ScEcotId column with FK back to Security).
* All Navigational Properties have IsManaged = True.
When I try the below code, I get
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Student_Security". The conflict occurred in database "ECOT_CM", table "dbo.Security", column 'ScEcotID'.
var dbStudentBeforeInsert = new Security
{
ScW2Klogin = "TEST",
ScUserType = 35
};
var person = new Person
{
PeFirstName = "Joe",
PeLastName = "Bob"
};
var student = new Student
{
StStatus = "INPROC"
};
dbStudentBeforeInsert.Person = person;
dbStudentBeforeInsert.Student = student;
_securityService.InsertAndSave(dbStudentBeforeInsert);
NOTE: I'm using a GenericRepository and Service pattern, so InsertAndSave looks like this:
public virtual TEntity InsertAndSave(TEntity entity)
{
this._context.Add(entity);
this._context.SaveChanges();
return entity;
}
I can successfully insert into 2 of the tables if I insert the child (Person or Student) with the parent (Security) attached, like this:
var dbStudentBeforeInsert = new Security
{
ScW2Klogin = "TEST",
ScUserType = 35
};
var person = new Person
{
PeFirstName = "Joe",
PeLastName = "Bob"
};
var student = new Student
{
StStatus = "INPROC"
};
student.Security = dbStudentBeforeInsert;
_studentService.InsertAndSave(student);
How can I insert the related entities from the parent (Security) insert so that I can insert into all 3 tables at the same time? Thx.