我有2个实体Person和Address,Person有一个Address.
编辑:地址已经存在,我只是想保存外键.
当我这样做:
PersonDTO person = new PersonDTO();
person.Age = "Bob";
person.Address = new AddressDTO {Key = 123};
Save(person);
我得到这个例外:
Cannot insert the value NULL into
column ‘Key’, table ‘Address’; column
does not allow nulls. INSERT fails.The
statement has been terminated.
从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>
我不明白为什么会发生这种情况,我给地址键一个值.我的做法有缺陷吗?
最佳答案 你需要这样做
AddressDTO add = new AddressDTO {Key = 123};
Save(add);
PersonDTO person = new PersonDTO();
person.Age = "Bob";
person.Address = add;
Save(person);
如果您不想显式保存地址,请修改映射:
<many-to-one name="Address" column="..." class="AddressDTO" cascade="save-update" />
如果地址已存在,则需要从数据库中获取:
PersonDTO person = new PersonDTO();
person.Age = "Bob";
person.Address = GetAddressDTO( 123 );
Save(person);