I would like to add a conditional property to an NHibernate entity using FluentNhibernate for mapping. I would also like to order by this property in my search criteria.
I have a list of contracts, which I would like to flag as expired or not based on the passing of the EndDate property on the contract. As for the order, I would like expired contracts to drop to the bottom of the list.
My desired outcome as a T-SQL statement;
SELECT ID, BeginDate, EndDate, CASE WHEN EndDate > GETDATE() THEN 1 ELSE 0 END AS Expired
FROM myTable
ORDER BY CASE WHEN EndDate > GETDATE() THEN 1 ELSE 0 END;
Is this possible with FluentNHibernate?
My (scrubbed) entity;
namespace MyDomain.Entities
{
public class MyEntity
{
// [ID] [int] IDENTITY(1,1) NOT NULL
public virtual int ID { get; private set; }
// [IsDeleted] [bit] NOT NULL
public virtual bool IsDeleted { get; set; }
// [BeginDate] [datetime] NOT NULL
public virtual DateTime BeginDate { get; set; }
// [EndDate] [datetime] NOT NULL
public virtual DateTime EndDate { get; set; }
}
}
My mapping for that entity;
namespace MyDomain.Mappings
{
public class MyEntityMap : ClassMap<MyEntity>
{
public MyEntityMap ()
{
this.Table("myTable");
this.Id(x => x.ID);
this.Map(x => x.IsDeleted);
this.Map(x => x.BeginDate);
this.Map(x => x.EndDate);
}
}
}
Yep. You can specify the CASE statement as a Formula:
This formula is obviously get-only, but must be set into a field or property (forcing you to define said field or property with public getter and setter, unless using some other tricks to set a private backing field). In this specific case, you may be better off defining this logic in a property getter, UNLESS you need to use this calculation in a query, or you need the DB server’s local time instead of the client machine’s.