0

A seemingly simple problem turns out more difficult than I thought:

public class SomeCategory 
{
    public virtual int Id { get; set; }
    public virtual IList<SomeClass> SomeInstances { get; set; }
}

public class SomeClass
{
    public virtual int Id { get; set; }
}

There is a 1:m relationship between SomeClass and SomeCategory (i.e. an instance of SomeClass belongs to exactly one SomeCategory and SomeCategory can have several SomeClass instances).

Question how do I get the SomeCategory given a SomeClass Id (Linq to NHibernate)?

cs0815
  • 16,751
  • 45
  • 136
  • 299

2 Answers2

3

I assume you will have access to SomeCategory list, then try

var category = someCategoryList.FirstOrDefault(e => e.SomeInstances
                               .Any(a => a.Id == someclassId));
Esteban Elverdin
  • 3,552
  • 1
  • 17
  • 21
  • I think this will also work var test = (from c in session.Query() from c1 in t.Classes where c1.Id == id select c).FirstOrDefault(); – Fran Oct 16 '13 at 16:45
1

You can also do it using QueryOver.

Parent parentAlias = null;
Child childAlias = null;

var query = session.QueryOver<Parent>(() => parentAlias)
                   .JoinAlias(()=> parent.Childs, ()=> childAlias)
                   .Where(()=> childAlias.Parent.Id == id)
                   .Select(()=> childAlias.Parent)
                   .SingleOrDefault();
cidico
  • 386
  • 1
  • 10
  • Completely offtopic, can someone explain why NH has an API that looks like that? why argless lambdas? – Roger Johansson Oct 15 '13 at 11:32
  • The QueryOver API is the strongly-typed version of ICriteria's API. The argless lambdas act just like an alias in the SQL. Also, it helps you to construct queries without the need of forcedly refer to the QueryOver class. I really prefer the QueryOver over LINQ queries. It's much more readable even when building dynamic queries. :) – cidico Oct 15 '13 at 13:48