Search code examples
nhibernatefluent-nhibernate

NHibernate Mapping - total records. (Fluent Nhibernate)


I have class class1 with some properties and a Mapper class Class1Map which is mapped to table1 in DB.

i need to get top 10 records from table1 along with total number of records in table in a single query using NHibernate.

i added new property in class1 'total records' . How can I map this in class1Map.


Solution

  • This will be performance problem. You will execute subquery for each row.

    I dont recommend this . If you want , Add formula to your mappings

    Id(x => x.Id).Column("id").GeneratedBy.Identity();
    Map(x => x.PropA).Column("propA").Nullable();
    Map(x => x.TotalRecords).Formula("(select Count(1) from tableA)");
    

    I recommend. 1- get totalRecords of table before execute query 2- Execute your query. 3- set your property like this:

    var recordsCount  = Session.Query<TableA>().Count();
    var objects = Session.Query<TableA>().Where(yourExpression).Take(10);
    objects.Foreach(f=> f.TotalRecords = recordsCount);
    
    return objects;