更新时间:2023-12-01 18:17:28
Ah, it's actually very simple, once you think about it.. What you're trying to do it add the resource to the data context, even though this resource object was received from the database in the first place. So the error is not complaining about your child objects, but about your parent object! :)
Basically if you comment the first line in the SaveResource() method it should just work fine! E.g.:
public void SaveResource(Resource resource)
{
// context.AddToResources(resource); //Should also add children.
context.SaveChanges();
}
Or just move the AddChildResource method to your DAL:
public void AddChildResource(int parentResourceId, Resource childResource)
{
Resource parentResource = repository.GetResource(parentResourceId);
ResourceEdge inEdge = new ResourceEdge();
inEdge.ToResource = childResource;
parentResource.ToEdges.Add(inEdge);
context.SaveChanges();
}