How to make NHibernate requests with a link as a criterion?

I am trying to execute a query through NHibernate, where the criteria for the result depends on the table that is referenced. How should I do it? Consider 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 displayed in 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 the Foo from the database that reference a particular bar. This function uses criteria, but please give examples using something else if you think it’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; 
    }
}
+3
source share
1 answer

This is actually easier than you might think. Just add an equal constraint to the criterion using the property name and object directly:

public IList<Foo> GetAllFoosReferencingBar(Bar bar)
{
    using (var tx = Session.BeginTransaction())
    {
        var result = Session.CreateCriteria(typeof(Foo))
            .Add(Restrictions.Eq("ReferencedBar", bar) // <--- Added restriction
            .List<Foo>();
        tx.Commit();
        return result; 
    }
}
+2
source

Source: https://habr.com/ru/post/1737112/


All Articles