Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate: Mapping IList property

Tags:

c#

nhibernate

I have next tables Order, Transaction, Payment. Class Order has some properties:

public virtual Guid Id { get; set; }
public virtual DateTime Created { get; set; }
...

and I have added two more:

public virtual IList<Transaction> Transactions { get; set; }
public virtual IList<Payment> Payments { get; set; }

How to keep Transactions and Payments lists (relations) in the database?

like image 421
akrisanov Avatar asked Feb 27 '23 08:02

akrisanov


1 Answers

See collection mapping in the reference documentation. There are several ways to map an IList property.

A bag is an unordered, unindexed collection which may contain the same element multiple times.

<bag name="Transactions" lazy="true" table="Transaction" >
    <key column="OrderId"/>
    <one-to-many class="Transaction"/>
</bag>

A set is an unordered, unindexed collection which contains unique elements.

<set name="Transactions" lazy="true" table="Transaction" >
    <key column="OrderId"/>
    <one-to-many class="Transaction"/>
</set>

A list is an ordered and indexed collection which may contain the same element multiple times.

<list name="Transactions" lazy="true" table="Transaction" >
    <key column="OrderId"/>
    <index column="ordering"/>
    <one-to-many class="Transaction"/>
</list>

NHibernate can return the unordered collections in sorted order using the sort attribute.

No discussion of collection mapping us complete without mentioning cascade. This enables operations on the parent entity to apply to the collection entities.

  • It does not usually make sense to enable cascade on a <many-to-one> or <many-to-many> association. Cascade is often useful for <one-to-one> and <one-to-many> associations.
  • If the child object's lifespan is bounded by the lifespan of the parent object, make it a life cycle object by specifying cascade="all-delete-orphan".
  • Otherwise, you might not need cascade at all. But if you think that you will often be working with the parent and children together in the same transaction, and you want to save yourself some typing, consider using cascade="persist,merge,save-update"
like image 91
Lachlan Roche Avatar answered Mar 07 '23 06:03

Lachlan Roche