I have a web app that I am building using asp mvc with nhiberante 3.0.
I have the following code for querying my data –
ICriteria rowCount = session.CreateCriteria(typeof(entity1));
rowCount.SetResultTransformer(CriteriaSpecification.DistinctRootEntity)
.SetProjection(Projections.RowCount());
ICriteria query = session.CreateCriteria(typeof(entity1));
query.SetFetchMode("entity2", FetchMode.Eager);
query.SetResultTransformer(CriteriaSpecification.DistinctRootEntity);
query.SetFirstResult((pageIndex - 1) * pageSize);
query.SetMaxResults(pageSize);
query.Future<entity1>();
return new PagedList<entity1>(query.List<cshearin>(), pageIndex, pageSize, rowCount.List<Int32>().FirstOrDefault());
Now this is returning the correct data to my view, but the performance is awful. If I do not eager load entity2, the performance is great. The only problem with that is the view is then doing working with the data which I’ve read is not good practice.
Is it ok to have the view do this little bit, or is that bad practice? If it is bad practice, is there a better way that I can build this class for my data access?
Thanks for any thoughts.
EDIT – my mappings are pretty straightforward. Here is a simplified version.
entity1 –
<class name="entity1">
<id name="entity1_id">
<generator class="guid.comb"></generator>
</id>
<property name="column"></property>
<property name="column"></property>\
<bag name="entity2" cascade="all">
<key column="entity2_fk" />
<one-to-many class="entity2"/>
</bag>
</class>
and entity2 –
<class name="entity2">
<id name="entity2_id">
<generator class="guid.comb"></generator>
</id>
<many-to-one name="entity1" column="entity2_fk" />
<property name="columnx"></property>
<property name="columny"></property>
</class>
I will also have to look into using projections to pass to my view – that may be a valid answer.
You should find the reason of bad performance. Use a tool like Profiler (Sql Server) to see the queries generated by NH, or let NH write it to the console (show_sql) or log.
You may: