NHibernate uses classes to map into tables or views. Creating a Plain Old CLR Object
(POCOs, sometimes called Plain Ordinary CLR Objects) is a good practice for persistent classes. A POCO has its data accessible through the standard .NET property mechanisms, shielding the internal representation from the publicly visible interface.
namespace Project
{
public class Customer
{
public virtual string Id { get; set; }
public virtual string Name { get; set; }
public virtual char Sex { get; set; }
public virtual float Weight { get; set;}
public virtual bool Active { get; set;}
public virtual DateTime Birthday { get; set;}
public Customer()
{
}
}
}
NHibernate is not restricted in its usage of property types: all .NET types and primitives (like string, char and DateTime) can be mapped, including classes from the System.Collections
and System.Collections.Generics
namespaces. You can also map a relation between the entities, having properties that refer to another entity type. You can map them as values, collections of values, or associations to other entities. The property named Id
here is a special property that represents the database identifier (primary key) of that class, which is highly recommended for entities like a Cat. NHibernate can use identifiers internally only, without having to declare them on the class, but we would lose some of the flexibility in our application architecture.
No special interface has to be implemented for persistent classes nor do we have to subclass from a special root persistent class. NHibernate also doesn't use any build time processing, such as IL manipulation; it relies solely on .NET reflection and runtime class enhancement. So, without any dependency in the POCO class on NHibernate, we can map it to a database table or view.
For the above mentioned runtime class enhancement to work, NHibernate requires that all public properties of an entity class are declared as virtual
. The entity class must have a no-arguments constructor (protected
or public
) for NHibernate to create the objects.