(I've checked the related questions, and can't find an answer.)
I'm doing some tests with Code First Entity Framework 6. I have a "Child" entity that references two "Parent" entities.
I want to create the child entity and parent entities, and then save them all at once (so I can cut down on the number of db.Save() calls, and to keep it as one unit of work).
public class Child
{
public int ChildID { get; set; }
public string Name { get; set; }
public virtual Parent Father { get; set; }
public virtual Parent Mother { get; set; }
}
public class Parent
{
public int ParentID { get; set; }
public string Name { get; set; }
[ForeignKey("Child")]
public int? ChildID { get; set; }
public virtual Child Child { get; set; }
}
(A bit of a confusing setup -- the parents are actually the "children" of the child in the relationship. I know it's bad abstraction. This is just a test.)
Controller:
public ActionResult AddWithParents()
{
Parent father = new Parent { Name = "Test Father" };
Parent mother = new Parent { Name = "Test Mother" };
Child newChild = new Child
{
Name = "Test Child",
Father = father,
Mother = mother
};
db.Children.Add(newChild);
father.Child = newChild;
mother.Child = newChild;
db.SaveChanges();
return RedirectToAction("Index");
}
This works, but doesn't populate the Parent.ChildID foreign key.
If I do something like father.Child = newChild, I get the following error:
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details. Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values.
Is there any way to get this to work?