How do I make NHibernate delete child references when I delete a parent? - nhibernate

I have a NewsFeed object mapped as such:
<class name="NewsFeed">
<id name="NewsFeedId">
<generator class="guid"/>
</id>
<property name="FeedName" not-null="true" />
<property name="FeedURL" not-null="true" />
<property name="FeedIsPublished" not-null="true" />
</class>
And Users who can have a Set of Selected feeds that they might be intereseted in, mapped like so:
<class name="SystemUser">
<id name="SystemUserId">
<generator class="guid"/>
</id>
<set name="SelectedNewsFeeds" table="SystemUserSelectedNewsFeeds" cascade="all">
<key column="SystemUserId" />
<many-to-many column="NewsFeedId" class="NewsFeeds.NewsFeed, Domain"/>
</set>
</class>
What I want to happen is when I delete the parent NewsFeed then all of the SelectedNewsFeed references get deleted too, without having to load each SystemUser and delete the NewsFeed by hand.
What is the best way to achieve this?
UPDATE: Using cascade="all-delete-orphan" instead of "all" still results in an exception when deleting the NewsFeed:
The DELETE statement conflicted with the REFERENCE constraint "FKC8B9DF81601F04F4". The conflict occurred in database "System", table "dbo.SystemUserSelectedNewsFeeds", column 'NewsFeedId'.

JMCD
Your second approach:
Another alternative is to break the
many-to-many relationship with a join
class in the middle which nHiberate
would be able to determine
parent-child relationships and the
cascade should work.
is actually what the nHibernate folks recommend in their documentation.
Don't use exotic association mappings.
Good usecases for a real many-to-many
associations are rare. Most of the
time you need additional information
stored in the "link table". In this
case, it is much better to use two
one-to-many associations to an
intermediate link class. In fact, we
think that most associations are
one-to-many and many-to-one, you
should be careful when using any other
association style and ask yourself if
it is really neccessary.
Using two one-to-many associations adds the flexibility to easily add other attributes to the "subscription", such as notification preferences for that particular subscription.

Since the relation inside the set is many-to-many, nHibernate is not able to tell which end of the relationship is the child and which is the parent, and the quickest way for me to achieve what I wanted was just to write some SQL that I sent through my repository that deleted the respective news feeds from the collection, and then deleted the parent news feed. The next time the collection was hydrated the changes were reflected.
Another alternative is to break the many-to-many relationship with a join class in the middle which nHiberate would be able to determine parent-child relationships and the cascade should work.

change
cascade="all"
to
cascade="all-delete-orphan"
Reference

Related

Maintaining multiple one-to-many

Following on from NHibernate one-to-one vs 2 many-to-one
Is there an easy way to maintain multiple one-to-many relationships which are being used as a pseudo one-to-one.
E.g.
If I have 2 entities, User and Contact, which are related by a FK on each (User.ContactId and Contact.UserID).
What is the best way to maintain that each reference points at the other. It would be wrong for the system to update User with a different contact, but the Contact still references User...
Most likely you don't need to maintain this at all if you remove one of redundant foreign keys. Your database schema should not allow anomalies like that (userX references contactX but contactX references userY). Conceptually you have one-to-one relationship between user and contact. Why not have one-to-one in NHibernate mappings? If this is because of lazy loading that is not supported for nullable one-to-one in NHibernate? There is a solution to this problem that does not involve redundant foreign keys in the database.
1) In User mapping define a bogus list. List can have only one or zero items. Zero is treated as NULL (no Contact).
<bag
name="_contact"
table="UserContacts"
lazy="true"
inverse="true"
cascade="all-delete-orphan" >
<key column="UserId" />
<one-to-many class="Contact" />
</bag>
In Contact mapping define one-to-one:
<one-to-one name="_user" class="User" constrained="true" />
In the database you need to have PK Users.Id and one (!) foreign key Contacts.UserID.
2) Another option is to simply have many-to-one in User mapping and one FK Users.ContactId
<many-to-one
name="_contact"
column="ContactId"
cascade="all-delete-orphan"
unique="true"
lazy="proxy"/>
Either way the maintenance that you asked about is not needed and anomalies are not possible.

why doesn't NHibernate FetchMode.Join work in this scenario?

I have two entities, C and P.
C is mapped to P in a one-to-one association, with lazy="no-proxy",
like this: (P's mapping:)
<one-to-one name="c" class="C" property-ref="P" access="field" lazy="no-proxy"/>
P is mapped to C in a many-to-one association, like this: (C's mapping:)
<many-to-one name="p" column="PId" class="P" access="field" lazy="no-proxy" not-null="false"/>
usually I use lazy fetching, but in some cases I use FetchMode.Join to avoid the N+1 SELECTs problem, like this:
criteria.SetFetchMode("p", FetchMode.Join)
however, using FetchMode.Join for the C entity performs the query with a left outer join, and then immediately performs N more queries, fetching P's by ID! (profiling courtesy of NHProf)
any idea why this is happening?
answering #KLE's question, here's an excerpt from the documentation here
For a primary key association, add
the following mappings to Employee and
Person respectively:
<one-to-one name="person" class="Person"/>
<one-to-one name="employee" class="Employee" constrained="true"/>
Ensure that the primary keys of the related rows in the PERSON and EMPLOYEE tables are equal.
Alternatively, a foreign key with a
unique constraint, from Employee to
Person, can be expressed as:
<many-to-one name="person" class="Person" column="PERSON_ID" > unique="true"/>
This association can be made
bidirectional by adding the following
to the Person mapping:
<one-to-one name="employee" class="Employee" property-ref="person"/>
please let me know if I misunderstood this. thanks.
Don't know which version of NHibernate you are using but with 2.1.0 - 2.1.2 i've had some issues regarding FetchModes and complex mappings. I hadn't ran into property-ref (which obviously confuses the property walker) but i did have problems with some union classes.
Have you tried setting lazy="true" / "extra" and then define FetchMode.Join ?

When to use inverse=false on NHibernate / Hibernate OneToMany relationships?

I have been trying to get to grips with Hibernate's inverse attribute, and it seems to be just one of those things that is conceptually difficult.
The gist that I get is that when you have a parent entity (e.g. Parent) that has a collection of Child objects using a one-to-many mapping, setting inverse=true on the mapping tells Hibernate that 'the other side (the Child) has responsibility to update itself to maintain the foreign key reference in its table'.
Doing this appears to have 2 benefits when it comes to adding Children to the collection in your code, and then saving the Parent (with cascade-all set): you save an unneccessary hit on the database (because without inverse set, Hibernate thinks it has two places to update the FK relationship), and according to the official docs:
If the column of a
association is declared
NOT NULL, NHibernate may cause
constraint violations when it creates
or updates the association. To prevent
this problem, you must use a
bidirectional association with the
many valued end (the set or bag)
marked as inverse="true".
This all seems to make sense so far. What I don't get is this: when would you NOT want to use inverse=true on a one-to-many relationship?
As Matthieu says, the only case where you wouldn't want to set inverse = true is where it does not make sense for the child to be responsible for updating itself, such as in the case where the child has no knowledge of its parent.
Lets try a real world, and not at all contrived example:
<class name="SpyMaster" table="SpyMaster" lazy="true">
<id name="Id">
<generator class="identity"/>
</id>
<property name="Name"/>
<set name="Spies" table="Spy" cascade="save-update">
<key column="SpyMasterId"/>
<one-to-many class="Spy"/>
</set>
</class>
<class name="Spy" table="Spy" lazy="true">
<id name="Id">
<generator class="identity"/>
</id>
<property name="Name"/>
</class>
Spymasters can have spies, but spies never know who their spymaster is, because we have not included the many-to-one relationship in the spy class. Also (conveniently) a spy may turn rogue and so does not need to be associated with a spymaster. We can create entities as follows:
var sm = new SpyMaster
{
Name = "Head of Operation Treadstone"
};
sm.Spies.Add(new Spy
{
Name = "Bourne",
//SpyMaster = sm // Can't do this
});
session.Save(sm);
In such a case you would set the FK column to be nullable because the act of saving sm would insert into the SpyMaster table and the Spy table, and only after that would it then update the Spy table to set the FK. In this case, if we were to set inverse = true, the FK would never get updated.
Despite of the high-voted accepted answer, I have another answer to that.
Consider a class diagram with these relations:
Parent => list of Items
Item => Parent
Nobody ever said, that the Item => Parent relation is redundant to the Parent => Items relation. An Item could reference any Parent.
But in your application, you know that the relations are redundant. You know that the relations don't need to be stored separately in the database. So you decide to store it in a single foreign key, pointing from the Item to the Parent. This minimal information is enough to build up the list and the reference back.
All you need to do to map this with NH is:
use the same foreign key for both relations
tell NH that one (the list) is redundant to the other and could be ignored when storing the object. (That is what NH actually does with inverse="true")
These are the thoughts which are relevant for inverse. Nothing else. It is not a choice, there is only one way of correct mapping.
The Spy Problem:
It is a completely different discussion if you want to support a reference from the Item to the Parent. This is up to your business model, NH doesn't take any decisions in this. If one of the relations is missing, there is of course no redundancy and no use of inverse.
Misuse: If you use inverse="true" on a list which doesn't have any redundancy in memory, it just doesn't get stored. If you don't specify the inverse="true" if it should be there, NH may store the redundant information twice.
If you want to have an unidirectional association i.e. that the children can't navigate to the Parent. If so, you FK column should be NULLABLE because the children will be saved before the parent.

Fetch child without primary key NHibernate

I am trying to get a collection of objects into a parent object through mapping.
I have a parent object "ScoreCard" whose primary key is a guid (Id) and a child "Score" object whose primary key is a guid (Id). I want to select the child objects for the parent based on two fields that both objects have but I can't get it to work, here's the mapping
<bag name="ScoreCard">
<key>
<column name="HoleId"/>
<column name="PlayerId"/>
</key>
<one-to-many class="Score" not-found="ignore"/>
</bag>
I didn't design the database but the ScoreCard object comes from a view that returns both column I need plus the evil guid. Whatever I've tried, NHibernate keeps throwing an exception about the foreign key not being the same as the primary key.
This seems to me to be the most simple requirement, get a collection of things given some criteria, why am I so stuck?
Thanks for your help, sorry for the bad example code (subliminal golf watching at relatives house).
Well, I found it eventually. The parent object is drawn from a view giving three columns and no key. I can map a composite key to the HoleId and PlayerId instead of the evil guid that I found when I looked at the code. This is great as I can easily map the Score objects I need and then lazy load them using NHibernateUtil.Initialize.
My mapping xml needs to look like this
<class name="ParentObject">
<composite-id>
<key-property name="HoleId" column="HoleId" />
<key-property name="PlayerId" column="PlayerId" />
</composite-id>
<property name="EvilGuid" column="Id" />
<bag name="ScoreCard">
<key>
<column name="HoleId"/>
<column name="PlayerId"/>
</key>
<one-to-many class="Score" not-found="ignore"/>
</bag>
</class>
I got my inspiration from this post, please also pay attention to Stefan's answer as I feel I had a lucky break here, and the design could be made better with more thought about DDD.
Thanks for your help.
The problem is this: NHibernate works best (but not only) for DDD, this means for creating domain classes first and make the database best fitting the domain model.
You have a composite-id relation to non-primary-key fields. So start praying that NHibernate can cope with that. Both composite-ids and relations by non-primary-keys are supported - for legacy databases - and generally discouraged for DDD.
I think the combination of both does not work. See this issue on NHibernates issue tracker:
https://nhibernate.jira.com/browse/NH-1722. You can vote for the feature there.

NHibernate one-to-one mapping where second table data can be null

I have an existing database with the table Transactions in it. I have added a new table called TransactionSequence where each transaction will ultimately have only one record. We are using the sequence table to count transactions for a given account. I have mapped this as a one-to-one mapping where TransactionSequence has a primary key of TransactionId.
The constraint is that there is an instead of trigger on the transaction table does not allow updates of cancelled or posted transactions.
So, when the sequence is calculated and the transaction is saved, NHibernate tries to send an update on the transaction like 'UPDATE Transaction SET TransactionId = ? WHERE TransactionId = ?'. But this fails because of the trigger. How can I configure my mapping so that NHibernate will not try to update the Transaction table when a new TransactionSequence table is inserted?
Transaction mapping:
<class name="Transaction" table="Transaction" dynamic-update="true" select-before-update="true">
<id name="Id" column="ID">
<generator class="native" />
</id>
<property name="TransactionTypeId" access="field.camelcase-underscore" />
<property name="TransactionStatusId" column="DebitDebitStatus" access="field.camelcase-underscore" />
<one-to-one name="Sequence" class="TransactionSequence" fetch="join"
lazy="false" constrained="false">
</one-to-one>
</class>
And the sequence mapping:
<class name="TransactionSequence" table="TransactionSequence" dynamic-update="true">
<id name="TransactionId" column="TransactionID" type="Int32">
<generator class="foreign">
<param name="property">Transaction</param>
</generator>
</id>
<version name="Version" column="Version" unsaved-value="-1" access="field.camelcase-underscore" />
<property name="SequenceNumber" not-null="true" />
<one-to-one name="Transaction"
class="Transaction"
constrained="true"
foreign-key="fk_Transaction_Sequence" />
</class>
Any help would be greatly appreciated...
One to one mapping in nhibernate doesn't work the way you think it does. It's designed so that you have two classes, which when persisted to their corresponding tables have the same primary keys.
However you can make it work, but it's not pretty. I'll show you how then offer up some alternatives:
In your Transaction hbml:
<one-to-one name="Sequence" class="TransactionSequence" property-ref="Transaction"/>
In your Sequence html:
<many-to-one name="Transaction" class="Transaction" column="fk_Transaction_Sequence" />
This should do what you want it to do. Note the property-ref.
The next question you're going to post on is going to ask how you get lazy loading on one-to-one associations. The answer is, you can't... well you can, but it probably won't work. The problem is that you have your foreign key on the sequence table, which means that nhibernate has to hit the database to see if the target exists. Then you can try playing around with constrained="true/false" to see if you can persuade it to lazily load the one-to-one association.
All in all, it's going to result in a total waste of your time.
I suggest either:
Have two many-to-one associations.
Have a many-to-one association with a collection on the other end.
This will save you a lot of headaches in the long run.
Turns out that for my situation a <join table> mapping worked best. I just had to make sure that I made the properties that came from the second table were nullable types, or it would do an insert on save even if nothing had changed. Since I did not need lazy loading for the second table, this works great. I am sure that I could have gotten paired many-to-one mappings to work, but it was not intuitive and seems more complicated than the join table option, however <join table> is only available in NHibernate 2.0 and up.