Note that there are some explanatory texts on larger screens.

plurals
  1. POFluent NHibernate sometimes does not find record (returns null)
    text
    copied!<p>I fetch a mapped entity with</p> <pre><code>using (var session = myFactory.OpenSession()) { using (var transaction = session.BeginTransaction()) { try{ var myEntity = session.Get&lt;T&gt;(myId); ... transaction.Commit(); if (myEntity == null) throw new ObjectNotFoundException(id, typeof(T)); return myEntity; } catch (HibernateException ex) { // logging if (!transaction.WasCommitted) transaction.Rollback(); throw ex; } } // transaction } // session </code></pre> <p>The problem is that sometimes the entity is found and sometimes not.</p> <p>No entity modification is performed when the program is launched.</p> <p>If I stop the execution after <code>session.Get()</code> and execute the NHibernate generated SQL, the row is found.</p> <p>If I stop the execution after <code>session.Get()</code> and in the Watch section of Visual Studio execute the same statement with another valid id, then the other entity is found, too.</p> <p>After <code>session.Get()</code>, <code>session.IsConnected</code> and <code>session.IsOpen</code> return <code>true</code>.</p> <p>Why does NHibernate not find the entity?</p> <p><strong>EDIT</strong></p> <p>Here are hash code and equals method. The Id is a string.</p> <pre><code>public override int GetHashCode() { int hashCode = 0; hashCode = hashCode ^ Id.GetHashCode(); return hashCode; } public override bool Equals(object obj) { if(obj.GetType()!=typeof(MyEntity)) return false; MyEntity compareTo = obj as MyEntity; return compareTo.Id == this.Id; } </code></pre> <p><strong>EDIT2</strong></p> <p>When the entity is found and I call <code>session.QueryOver&lt;MyEntity&gt;().List().ToList()</code>, then all other entities are found except the one I requested.</p> <p><strong>EDIT3</strong></p> <p>I had defined one relation which was mapped with <code>.Column("colName").Access.ReadOnly()</code>. Now when the program (i.e. a view that uses the entity) was loaded, there was an attempt to update the relation. This, however, probably failed because the relation was not loaded from the database (<code>.Column("colName").Access.ReadOnly()</code>) and the foreign key constraint was not respected. From that point on, the requested entity could not be found anymore.</p> <p>Now I just wonder why my entity could not be loaded when I restarted the application, since the changes (null foreign key reference) was NOT in the database (i.e. the database was still consistent).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload