I have many objects in my system that all inherit from a base class, Entity. These objects have quite a few relationships, including one-to-one, one-to-many, and many-to-many. Since I am using WCF, my DbContext object is disconnected with every CRUD call. This has caused me to run into some issues with basic CRUD operations on objects with relationships.
For example, I have an object with a basic parent-child relationship. I will call it Node.
[DataContract(IsReference=true)]
public partial class Node : Entity
{
[DataMember]
public long ID { get; private set; }
[DataMember]
public long? ParentID { get; set; }
[DataMember]
public List<Node> Children { get; set; }
}
I want to be able to add a new node that has a child that already exists and also to add a node that has a child that does not exist yet.
// Node with a new child node
Node nodeWithNewChild = new Node()
{
Children = new List<Node>()
{
new Node()
}
}
// A pre-existing child node
Node existingChildNode = new Node();
// Node with a pre-existing child node
Node nodeWithExistingChild = new Node()
{
Children = new List<Node>()
{
existingChildNode
}
}
The problem is that no matter how I go about it, Entity Framework gets confused.
When I use a basic DbContext.Nodes.Add operation, it messes up on my test case with an existing child. It makes a duplicate entry of the existing child in the database, and then gives this new child the correct ParentID. This also happens if I loop through the children and use DbContext.Nodes.Add on the children first.
I tried looping through all the children and using DbContext.Nodes.Attach on all the children and then using DbContext.Nodes.Add on the parent, but this causes an exception on my test case with a new child.
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries. ...
Not to mention I am worried about how this would work if, for example, you added a node with a child with a child with a child and so on. I want my CRUD methods to react appropriately to all possible valid object constructions.
From the research I have been able to find, it comes to down to the fact that EF is just not meant for or is just bad at this kind of thing, and it is best to manage relationships myself. Is this true? If so, is there an example I can follow? Any tips, etc.?
I started on a method that would handle relationships myself that uses reflection, but I feel like this is just a ridiculous way to solve what should be a basic problem.