This question isn't code-centric, it's a question about idioms. I'm using Backbone/Marionette on the front and C#, NHibernate in the back.
I've got a few tables mapped and working for creates and updates. For simplicity, say I've got two tables, a parent and child, and the child has potentially many rows. The child reference to the parent is not-nullable, so I've got an Inverse relationship, and that's all working. The flow of data from Backbone to the Controller to NHibernate is pretty simple, and I'm using ISession.SaveOrUpdate() at the end. I can post mappings and so forth if necessary. I will say that the mappings Fluent NHibernate generates uses a Bag on the parent.
Here's a concrete example of the situation I'm trying to understand. Say I've got a parent entry with two rows in the child table. I manipulate the data so that one of the children is removed, but no other changes are made. Javascript sends over an object "tree" with the parent entry and the one child row that's left. The mappings are all handled fine, but the sql that's generated is a bunch of (unnecessary, but whatever) update statements. What I would like to happen instead is that NHibernate notices that there is only one child relationship in this new object, but there are two children in the actual database, and then NHibernate deletes that other child. The 'cascade-delete-orphans' option is not working, because the other child isn't actually being orphaned. It still has a reference to the parent in the fk column, and that column is non-nullable anyway, which is why I used the Inverse mapping option.
Is that possible to setup in the mappings? If not, what is a good way to tackle this situation?
Since you are sending an object from the client side, and then create the entity from that object and try to persist, NHibernate will not automatically delete the child entity since it does not know the child object is deleted (it only see you are only try to update one parent entity and a child entity), which is correct in my opinion. For example if you want to just update the parent entity field, then you have to load entire object graph to do it, otherwise NHibernate will delete all children since they are not loaded.
What you should do here is to load the parent entity, and remove missing child entity(s) deleted from it and then persist (instead of mapping the entity), code should look like following,
void Update(ParentDto parentDto){
Parent parent = _session.Get<Parent>(parentDto.Id);
//update parent fields
var childRemoved = //find removed child from parent;
parent.Children.Remove(childRemoved);
_session.SaveOrUpdate(parent);
}
Related
Given this model:
I would like to be able to save in one SaveChange call the relations. Which means, I either have a new or updated ContainerParent, and multiple first level children and each of those can have 1 or 2 levels deeper.
The thing is, the children both have a key to themselves, for finding its parent, and a key to the container, for the container to get all its Children independently of their hierarchical level.
With this pseudo code (in the case of all entities are created, not updated)
var newContainerParent = context.ContainerParents.Add(new ContainerParent());
var rootChild = context.Children.Add(new Child());
var secondLevelChild = new Child();
var thirdLevelChild = new Child();
secondLevelChild.Children.Add(thirdLevelChild);
rootChild.Children.Add(secondLevelChild);
newContainerParent.Children.Add(rootChild);
context.SaveChanges();
Problem with this code, is that only the rootchild will have the FK for the container set. I also tried to add the children to they child parent AND the container:
rootChild.Children.Add(secondLevelChild);
newContainerParent.Children.Add(rootChild);
newContainerParent.Children.Add(secondLevelChild);
newContainerParent.Children.Add(thirdLevelChild);
I have the same problem while updating an existing container with new children. I set all the children with the already existing key of the parent, but when SaveChanges is called the key is not saved, its reverted to null.
I fixed it by doing all this in 2 steps, saving once and then getting all the newly created children and updating them with the parent key, the calling SaveChanges again.
I have a feeling I'm missing something, that I should not need to save twice.
The number or frequence of SaveChange calls have no implication on anything, not on performance or so. So why do you want to minimize it ?
Actually, storing such a self referencing table with one SaveChanges is not possible,
cause the ID of an new entity, is generated, when it is saved. So you first need to save it, and then you get the ID, that you can store in another entity. This might require further update-Commands, to the entity you just stored.
You have two chances to solve this.
1) manually generated ID's, handle it all yourself and you know the ID before your store it.
2) In case you have no circularity in your dependency, so a perfect tree structure, you save the items top-down, level by level. I assume you have the childs having a reference to it's parents, so the root has no reference to any other items, you save that first, than the 1st level children, and so on.
This requires multiple SaveChanges, but this is not a disadvantage. It is one Insert-SQL-Command per entity anyway, no matter if you do it in 1 SaveChanges or in 100 SaveChanges.
Both solutions avoid "Update" Commands to the entities, they do Inserts only.
Entity Framework could actually find out this dependencies itself and create an order for new entities to insert, but this is not implemented today, or not perfect, especially on self-referenced tables. The order of saving items is kind of random. So you have to enforce the order with intermediate SaveChanges.
I am working on a CAD application, where I have block entity. Each block entity have a list of child entities. When these entities are rendered, every block entity knows about its child entity (as it can figure out the child entity in the list), and hence when block entity is selected, the whole block entity along with its child entities gets selected. However, child entity does not know the parent block and other child entities of that block, and due to this when child entity is selected, I cannot get the whole block entity along with all its child entities selected.
As a fix to this problem I created a property in child entities to hold the reference of parent block entity. But, then there might be some issues with cross-referencing and making my data structures error prone.
For Ex: Having a Copy command, somebody working on these data structures few days from now, might just copy the same parent while creating a copy of child entity. However, new copy should belong to some other parent block.
Please suggest the better way to implement this relationship, so that when a child entity is selected I can select whole block entity along with all its child entities.
public class BlockEntity
{
public List<ChildEntity> Children = new List<ChildEntity>();
}
public class ChildEntity
{
public readonly BlockEntity Parent;
}
I have recently come across this issue. I, and others I talked with, came up with two choices:
Do what you are doing with the Parent<-->Child relationship, both knowing about each other.
Have a Parent-->Child relationship and make everything be handled at the parent.
Both are viable solutions, but both have their issues. The first case, what you are doing, seems better and Microsoft seems to use this with their TreeView/TreeNode and DataTable/DataRow/etc. objects for example, because they can each reference back to their respective parents.
Maybe add constraints to the parent, such as not allowing access to the parent's child-collection directly, but only allowing an AddChild function in which you can do the necessary linking. Or do what #Irfan suggests and have the child require you pass the parent to its constructor. Constrain your copy method as well, but always document everything to remove as much confusion as possible.
The later of the above examples is a little easier as everything is always accessed from the parent. This was our solution. We have many functions in the parent to check for and manage the children within. So in this case you would select the child in the CAD app then go to the parents and check in their collection to see if the child exists there. If it does you select the parent and the rest of the children.
It's up to you, but in each case you need to add constraints and error checking to make sure things happen as close to your desired way as possible. Hope this helps.
what reference problems will you get by creating a reference to parent? With this readonly reference which can only be set during construction of the object I see no problem at all.
The Contructor (I am sure you know) looks like:
public ChildEntity(BlockEntity p)
{
Parent = p;
}
//Test just to show Parent can not be assigned elsewhere
public void test()
{
//this line below will show compile error
Parent = new BlockEntity();
}
Do you think there would be some problem with this. The list is a loose reference so there is no stack overflow exception.
I have a bidirectional one to many relationship defined with cascade="all" defined on both ends in the mapping and inverse="true" on the one-to-many end.
When I call SaveOrUpdate a new entity the it correctly inserts a row into the parent table, then inserts all the child objects in the child table.
However, if I have an existing entity and update some properties of the child objects (say alter some string properties) then call SaveOrUpdate on the parent entity, it only updates the information in the parent table. I was expecting it to update all the child entities also.
Is this the expected behaviour? Do I need to manually update all the child objects myself? I'm not sure if I've messed something up in my mappings (in which case I'll add them to the question) or if this is how NHibernate is supposed to behave.
Edit: found the error; problem exists between keyboard and chair as usual.
Never mind, I was just being stupid and updating a property that isn't mapped to any columns.
Looks like NH will update child records that need updating only.
I have an intermittent problem in a production system that I haven't been able to recreate locally. What appears to be happening is that for no obvious reason during an edit of a child entity and saving the parent containing the collection the parent association on the child entity is removed in the database. Effectively orphaning the child entity.
Here is the fluent mapping:
mapping.HasMany<ExpenseItem>(x => x.ExpenseItems).Cascade.AllDeleteOrphan();
The entity can also be directly saved (it is also aggregate root), but during testing this has not be shown to remove the parent association.
There are no references to the parent itself in the child object the association is all in the DB handled by Nhibernate.
There is also no possibility of assigning the same child entity to another parent as expense item (child entity) cannot be added outside of its parent directly. See code below.
public virtual ExpenseItem AddNewExpenseItem(ExpenseAnalysis analysis,
string recipientName,
string purchaseAccountReference,
string expenseDescription,
string expenseNotes,
Money value,
VATAnalysis vat)
{
Validate.IsNotNull<ExpenseAnalysis>(analysis);
Validate.IsNotNull(expenseDescription);
....
ExpenseItem newExpenseItem = new ExpenseItem(analysis,
recipientName,
purchaseAccountReference,
expenseDescription,
expenseNotes,
value,
vat,
expenseItemUniqueReference,
true,
Candidate.Assessment);
_expenseItems.Add(newExpenseItem);
....
Any ideas?
It would definitely help to see your mapping but take a look at
I'd also map the ExpenseItem with a reference to its parent
How to delete child object in NHibernate?
basically you ve to set inverse on the relationship so that NHibernate does not try to update the deleted record with a null victim. And you set Cascade.All | Cascade.DeleteOrphans so that we aren't just breaking the relationship by nulling out the victim, but deleting the entire child record.
This problem was caused by a bug in NHibernate. I had set the session to flush never however when you call isdirty on the session the session was being flushed first. The user was deleting the expense item then cancelling the edit but during the isdirty check the deletion was being flushed. Managed to work around this by changing how the session was being managed for this type of dialog.
Is it possible to pass a reference at load time of a parent to it's children without a relationship back to the parent from the child?
I would prefer to NOT have a mapped property for this purpose (i.e. prefer not to use bi-directional relationships for this purpose).
You could probably do it with a linking table but you'd have to enforce one-to-many via code otherwise it could easily become a many-to-many. The jist of the linking table would be that it keeps the association between the parent and its children, rather than the child object itself.