Dan
Dan

Reputation: 29375

NHibernate: Column does not allow nulls. INSERT fails

I have 2 entities Person and Address, Person has one Address.

EDIT: The Address already exists, Im just wanting to save the foreign key.

When I do this:

  PersonDTO person = new PersonDTO();
    person.Age = "Bob";
    person.Address = new AddressDTO {Key = 123};
    Save(person);

I get this exception:

Cannot insert the value NULL into column 'Key', table 'Address'; column does not allow nulls. INSERT fails.The statement has been terminated.

Mapping file fragment from Person

<class name="PersonDTO" table="Person" xmlns="urn:nhibernate-mapping-2.2">
    <id name="Key" column="PersonKey" type="Guid">
      <generator class="guid" />
    </id>
    <one-to-one name="Address" class="AddressDTOl" />
  </class>

I don't understand why this happens, im giving Address Key a value. Is my approach flawed?

Upvotes: 4

Views: 5270

Answers (3)

Dan
Dan

Reputation: 29375

Fixed it!

I changed my fluent nhibernate mapping, I used a References Relationship instead of HasOne.

This resulted in changing the mapping to this:

<many-to-one name="Address" column="AddressKey" />

Upvotes: 0

mathieu
mathieu

Reputation: 31202

You need to do this

AddressDTO add = new AddressDTO {Key = 123};
Save(add);

PersonDTO person = new PersonDTO();
person.Age = "Bob";
person.Address = add;
Save(person);

Or modify your mapping if you don't want to explicitly save Address :

<many-to-one name="Address" column="..." class="AddressDTO" cascade="save-update" />

If the address already exists, you need to get it from database :

PersonDTO person = new PersonDTO();
person.Age = "Bob";
person.Address = GetAddressDTO( 123 );
Save(person);

Upvotes: 2

Graham Ambrose
Graham Ambrose

Reputation: 1999

You should save the address before saving the person. Depending on the generator you may have to use the save overload that passes in the ID.

If you need the save to be implicit you should set the cascade of address property in the person.

Upvotes: 0

Related Questions