51

I have a mapping along the lines of this.

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Model.Entities" schema="etl" assembly="Model" default-lazy="false">
  <class name="Model.Entities.DataField, Model" table="mdm_field">
    <id name="FieldId" column="field_id" type="int">
      <generator class="native" />
    </id>
    <many-to-one name="KeyField" class="Model.Entities.Key, Model" column="field_id" />
  </class>
</hibernate-mapping>

Now in the database the field_id in the mdm_field table sometimes has a value that does not exist in the related key_field table, so it is basically broken referential integrity. Because of this when I load the entity I get an error "No row with the given identifier exists". How do I configure the mapping to work with this situation so it will not die on this situation.

Craig
  • 36,306
  • 34
  • 114
  • 197

3 Answers3

81

Ok, I found the answer. Add the

not-found="ignore"

attribute to the property KeyField:

<many-to-one name="KeyField" not-found="ignore" class="Model.Entities.Key, Model" column="field_id" />
Răzvan Flavius Panda
  • 21,730
  • 17
  • 111
  • 169
Craig
  • 36,306
  • 34
  • 114
  • 197
  • 2
    This tripped me up, too. For annotations use @NotFound(action=NotFoundAction.IGNORE). – NobodyMan Nov 08 '10 at 23:23
  • 6
    I'm running into a similar problem with Fluent NHibernate. Ted, if you could point to a proper fix, I'd be very appreciative. FWIW, putting .NotFound.Ignore() on the KeyField didn't help in my case anyway. – BobC Dec 21 '11 at 22:30
  • 1
    @Ted Care to elaborate as to why it isn't a valid workaround? – The_Butcher Aug 15 '12 at 07:32
  • 1
    @The_Butcher Ted is correct since putting 'not-found=ignore' it doesn't raise the exception, but it will get rid of lazy initialization! Do you want to select 10000 times if you have a list of 10000 items? – Stefano.net Sep 19 '12 at 16:12
  • Apart from probably not being the optimal solution anyway, this did not work for me using fluent NHibernate NotFound.Ignore() on the mapping. – Rev Dec 11 '12 at 11:29
5

In my case the problem was because a foreign key constraint was not enforced by MyISAM engine and therefore one of the rows ended up pointing to a non-existant value and the proxy threw an exception. I would recommend checking your dataset is consistent in this case.

Shagglez
  • 1,522
  • 3
  • 21
  • 38
4

Try that...

public void Override(ModelMapper modelMapper) {
    modelMapper.Class<T>(c => { 
        c.ManyToOne(m => m.FKObj, r => {
            r.Column("FKColumn");
            r.NotFound(NotFoundMode.Ignore); // THIS IS IMPORTANT!!!
        });
    });
}
Rodolpho Brock
  • 8,027
  • 2
  • 28
  • 27