NHibernate: Column does not allow zeros. INSERT does not work

I have 2 objects Person and Address, a person has one address.

EDIT: The address already exists, I just want 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 a NULL value in the Key column, Address table; column does not allow null. INSERT fails. approval completed.

Displaying a fragment of a file 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 do not understand why this is happening, I give the Address Key value. Is my approach wrong?

+4
source share
3 answers

Fixed!

I changed the fluent nhibernate mapping, I used the Links link instead of HasOne.

This led to a mapping change to this:

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

You need to do it

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

Or change your mapping if you don't want to explicitly save the address:

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

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

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

You must save the address before saving the person. Depending on the generator, you may need to use the overload that passes in the identifier.

If you want the persistence to be implicit, you must set the property of the address cascade in person.

0
source

All Articles