简体   繁体   中英

Nhibernate Queryover, how to access nested proeprty

this is my model

public class A{
    public int Id {get; set;}
    public ICollection<B> bs {get; set;}
}

public class B{
    public int Id {get; set;}
    public ICollection<C> cs {get; set;}
}

public class C{
    public int Id {get; set;}
}

now i want to get Max(Id) of C class of a B object of an A object:

public int GetMaxId(int idA, int idB)

i try some diffente way:

var max= _session.QueryOver<A>().Select(a => a.Bs)
.Where(a => a.Id == idA).SingleOrDefault<ICollection<B>>()
.Where(b => b.Id == idB).FirstOrDefault<B>().Cs.Max(c => c.Id);

and

var max = _session.QueryOver<A>().Where(a => a.Id == idA).Select(a => a.Bs.Where(b => b.Id == idB)).Future<B>().Max(c => c.Id);

but nothing works

any way to do this? Thanks

First of all be aware that SingleOrDefault and FirstOrDefault end your query. All that comes after will be processed in memory, not on the database! Besides that, you have a chance of a NullReferenceException after these methods.

To use nested properties in the QueryOver API you need to use aliases. As shown here under heading 'Aliases'.

But the simplest way in my opinion is to use LINQ instead:

_session.Query<A>()
    .Where(a => a.Id == idA)
    .SelectMany(a => a.Bs)
    .Where(b => b.Id == idB)
    .SelectMany(b => b.Cs)
    .Max(c => (int?)c.Id) // the cast makes sure you don't get a null reference (tnx to gt.guybrush)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM