I'm trying to do a query through NHibernate where the criterion for the result depends on a referenced table. How do I do this? Let's look at a simple example:
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; }
}
Foo is then mapped to Bar:
public class FooMapping : ClassMap<Foo>
{
public FooMapping()
{
Id(c => c.Id).GeneratedBy.HiLo("1");
Map(c => c.Name).Not.Nullable().Length(100);
References(c => c.Bar);
}
}
Now I want to get all Foo's from the Database which reference a specific Bar. This function is using Criteria, but please give examples using something else if you think that's better:
public IList<Foo> GetAllFoosReferencingBar(Bar bar)
{
using (var tx = Session.BeginTransaction())
{
var result = Session.CreateCriteria(typeof(Foo))
.Add(Restrictions./* foo.ReferencedBar == bar */) // <-- How to add restriction using reference?
.List<Foo>();
tx.Commit();
return result;
}
}