Search code examples
c#nhibernatemapping

NHibernate Map an Object without a table


I'm trying to map the following object:

public class DatabaseInfo
{
    public virtual DateTime CurrentDateTime { get; set; }
}

with the following map:

public class DatabaseInfoMap : ClassMapping<DatabaseInfo>
{
    public DatabaseInfoMap()
    {
        Property(x => x.CurrentDateTime, map => { map.Formula("(SELECT CURRENT UTC TIMESTAMP AS CurrentDateTime)"); });
    }
}

I am getting a validation error, as the Map does not contain a 'Table' definition. Is it not possible to map obejcts without having to make a Table or View?

I'm not sure if this is the right approach for me to get the database time via NHibernate. Any help is appreciated.


Solution

  • Since there is no table mapping as an entity makes no sense (no identity). I suggest:

    public class DatabaseInfo
    {
        public static DatabaseInfo Get(ISession session)
        {
            return session.CreateSQLQuery("SELECT CURRENT UTC TIMESTAMP AS CurrentDateTime").SetResultTransformer(Transformers.AliasToBean<DatabaseInfo>()).UniqueResult<DatabaseInfo>();
        }
    
        public DateTime CurrentDateTime { get; protected set; }
    }