views:

48

answers:

1

I want to map the following company to the below address. I want it to be a one way relationship since the address class is being used by several other classes.

When I generate the schema the junction table is created successfully but when I try to save an entity nothing is persisted in the junction table. Only in address and company tables. What do I need to do to make this work?

public CompanyMapping()
{
    Map(x => x.Name);

    HasManyToMany(x => x.Addresses);
}

public AddressMapping()
{
    Id(x => x.Id);

    Map(x => x.AddressLineOne)
        .Not.Nullable();

    Map(x => x.AddressLineTwo)
        .Nullable();

    Map(x => x.PostCode)
        .Not.Nullable();

    Map(x => x.City)
        .Not.Nullable();
}

public class HasManyToManyCascadeConvention : IHasManyToManyConvention
{
    public void Apply(IManyToManyCollectionInstance instance)
    {
        instance.Cascade.All();
        instance.Inverse();
        instance.Key.ForeignKey(Inflector.Underscore("fk_" + instance.EntityType.Name + "_" + instance.ChildType.Name));
    }
}

<class xmlns="urn:nhibernate-mapping-2.2" name="Company" table="`company´">
    <id name="Id">
        <column name="company_id" />
        <generator class="identity" />
    </id>
    <bag table="company_address" lazy="false" cascade="save-update" name="Addresses">
        <key column="company_id" />
        <many-to-many class="Address" column="address_id" />
    </bag>
    <property name="Name">
        <column name="name" />
    </property>
</class>

EDIT 2010-11-05: If I add mappings for BillingAddress and DeliveryAddress like this I don't have any problems.

References(x => x.BillingAddress)
    .Column("billing_address_id")
    .ForeignKey("fk_account_billing_address")
    .Cascade.All()
    .Fetch.Join();

References(x => x.DeliveryAddress)
    .Column("delivery_address_id")
    .ForeignKey("fk_account_delivery_address")
    .Cascade.All()
    .Fetch.Join();
A: 

You need to tell nHibernate which side of the collection wears the pants. See if this works:

HasManyToMany(x => x.Addresses)
    .Inverse()
    .Cascade.All();
Gabe Moothart
Doesn't work. I updated the code with one of the conventions. I'll post the xml as well
mhenrixon
I've tried with inverse, not inverse. With forreign keys without keys etc etc but it produces the same result. Nothing is persisted in the join-table.
mhenrixon
Are your saves wrapped in a transaction?
James Gregory
Not when running the unit tests but I have the same issue while debugging the application.
mhenrixon
Did you let nHib auto-create the mapping table (via schema update)? If not you may need to add additional configuration to tell nHib about it.
Gabe Moothart
Yes it was autocreated but is not being used more than that and my guess is because it's not referenced from the address class / mapping
mhenrixon