I’ve aske a question a few days ago My previous question. So my question was how to get ordered by property of a propery and distinct list of objects. At that time i was trying to achieve this by using QueryOver, but now i’m using Criterea API. And i have equal records again. This is my criterea
var lst =
Session.CreateCriteria<News>().CreateAlias("Category", "c").AddOrder(Order.Asc("c.Name")).
SetFirstResult(pageSize * pageNumber).SetMaxResults(pageSize).List<News>();
if i’m trying to add Distinct projection, I get nothing. Just exception Unable to perform find[SQL: SQL not available].
var lst =
Session.CreateCriteria<News>().SetProjection(Projections.Distinct(Projections.Id())).CreateAlias("Category", "c").AddOrder(Order.Asc("c.Name")).
SetFirstResult(pageSize * pageNumber).SetMaxResults(pageSize).List<News>();
Classes
public class News
{
public virtual int Id { get; protected set; }
public virtual string Topic { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
public virtual int Id { get; protected set; }
public virtual string Name { get; set; }
public virtual ISet<News> News { get; set; }
}
And mappings
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="News" namespace="NewsManagement.Models">
<class name="News" table="News">
<id name="Id">
<generator class="native" />
</id>
<property name="Date" not-null="true" />
<many-to-one name="Category" fetch="join" column="CategoryId" class="Category, NHibernateManyToOne" not-null="true"/>
</class>
</hibernate-mapping>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="News" namespace="NewsManagement.Models">
<class name="Category" table="Categories">
<id name="Id" column="Id">
<generator class="native" />
</id>
<set name="News" fetch="join" cascade="all-delete-orphan">
<key column="CategoryId" />
<one-to-many class="News, NHibernateOneToMany" />
</set>
</class>
</hibernate-mapping>
If there is no way to get what i need with criterea API, how can i achieve required functionality?
And this is very important that i need to get distinct result from base, not making it distinct on client.
If you want to get order by c.Name then you have to use NHibernate DTO and add projection for c.Name.
Because order by column must present in the select item of the query.
http://www.junasoftware.com/blog/nhibernate-setresulttransformer-and-dto.aspx
http://elegantcode.com/2007/10/30/nhibernate-projections/