简体   繁体   中英

NHibernate not deleting record from joined table, updating it to null

My mapping (edited and dumbed down to protect the not-so-innocent):

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
           assembly="MyAssembly, Culture=neutral"
           namespace="MyAssembly" auto-import="false">
  <class name="Customer" table="Customers">
    <id name="Id" access="nosetter.camelcase-underscore" >
      <generator class="assigned"/>
    </id>
    <property name="blah"/>
    ...
    <property name="bleh"/>
    <join table="Addresses" optional="true">
      <key column="Id"/>
      <component name="Address" class="MyAssembly.Address, MyAssembly, Culture=neutral" access="field.camelcase-underscore">
        <property name="Street" />
        <property name="Number" />
      </component>
    </join>
  </class>
</hibernate-mapping>

When I do this:

Address dir = new Address();
dir.Street = "Foo";
dir.Number = 27;
//// Previously loaded customer
cli.Address = dir;
//// Save repository, commit transaction

That works fine, and automatically inserts the new address to the Address table. BUT, if I want to delete the address:

//// Previously loaded customer with attached address
cli.Address = null;
//// Save repository, commit transaction  

That, instead of deleting the row from the Addresses table NHibernate updates it, setting all its fields to null except Id.

What's wrong with my mapping?

Given your mapping, NHibernate performs correctly. The join-clause is for when a single object is to be spread over multiple tables. Typically there will always be one row in each table for the object.

Component mapping on the other hand is when you want a fine-grained object model, but store the data in the same table as the owning class. If the property is null, NHibernate can do nothing other than set all the columns used by the component to null. The fact that the component columns are the only non-key columns in the joined table is irrelevant.

Perhaps you are looking for one-to-one mapping instead? http://nhibernate.info/doc/nh/en/index.html#mapping-declaration-onetoone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM