-1

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

gt.guybrush
  • 1,320
  • 3
  • 19
  • 48

1 Answers1

2

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)
Pidon
  • 275
  • 1
  • 6
  • In my LINQ example there is no chance of a null. Or do you mean a different query? – Pidon Mar 13 '17 at 10:50
  • some problem in my unit test sorry, iam trying it :D – gt.guybrush Mar 13 '17 at 11:03
  • with no row in a,b and c table i get this error: System.Argument.NullException: value cannot be null. parameter name: item – gt.guybrush Mar 13 '17 at 13:14
  • An `ArgumentNullException` looks like it is executing in memory. Are you sure the exception is thrown from the query? Can you post a stacktrace? – Pidon Mar 13 '17 at 14:14
  • solved in this way: .Max(c => (int?) c.Id) found on http://stackoverflow.com/questions/341264/max-or-default. if you edit your answer i will mark it as accepted – gt.guybrush Mar 13 '17 at 16:09