nHibernate, No row with the given identifier exists
Asked Answered
T

3

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.

Thompkins answered 30/3, 2009 at 3:37 Comment(1)
I have the same mapping, do you know how to find all Models without KeyField?Tiling
T
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" />
Thompkins answered 30/3, 2009 at 3:46 Comment(5)
This tripped me up, too. For annotations use @NotFound(action=NotFoundAction.IGNORE).Dessertspoon
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.Araxes
@Ted Care to elaborate as to why it isn't a valid workaround?Compete
@Compete 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?Herodias
Apart from probably not being the optimal solution anyway, this did not work for me using fluent NHibernate NotFound.Ignore() on the mapping.Westerman
S
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.

Starbuck answered 27/6, 2013 at 11:4 Comment(1)
Thanks for your answer! This actually solved the issue instead of working around it.Vitriolize
F
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!!!
        });
    });
}
First answered 5/11, 2014 at 17:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.