开发者

How to do NHibernate queries with reference as criterion?

开发者 https://www.devze.com 2022-12-23 15:29 出处:网络
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:

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开发者_Go百科(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; 
    }
}


This is actually easier than one might think. Just add an Equal restriction to the critierion using the property name and the 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; 
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消