Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to do NHibernate queries with reference's id as criterion?
    primarykey
    data
    text
    <p>I'm trying to do a query through NHibernate where the criterion for the result depends on a referenced table's ID. How do I do this? Let's look at a simple example:</p> <pre><code>public class Foo { public int Id { get; set; } public string Name { get; set; } public Bar ReferencedBar { get; set; } } public class Bar { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>Foo is then mapped to Bar:</p> <pre><code>public class FooMapping : ClassMap&lt;Foo&gt; { public FooMapping() { Id(c =&gt; c.Id).GeneratedBy.HiLo("1"); Map(c =&gt; c.Name).Not.Nullable().Length(100); References(c =&gt; c.Bar); } } </code></pre> <p>Now I want to get all Foo's from the Database which reference a specific Bar by id. This function is using Criteria, but please give examples using something else if you feel it's better:</p> <pre><code>public IList&lt;Foo&gt; GetAllFoosReferencingBar(int barId) { using (var tx = Session.BeginTransaction()) { var result = Session.CreateCriteria(typeof(Foo)) .Add(Restrictions./* foo.ReferencedBar == id */) // &lt;-- How to add restriction using id? .List&lt;Foo&gt;(); tx.Commit(); return result; } } </code></pre> <p>When I try to do this with, I get the exception:</p> <pre><code>.Add( Restrictions.Eq( "ReferencedBar", 32 ) ); </code></pre> <p>Type mismatch in NHibernate.Criterion.SimpleExpression: ReferencedBar expected type Bar, actual type System.Int32</p> <p>I do not have a reference object to Bar with id 32 yet and do not want to create one...</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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