Attributes in NHibernate
It's been a long time since i post to this blog. I'm still busy with my CISCO stuff, and also have to train some end-user to use my software, and i work alone. I work as a .NET freelancer (my team is just me and one of my friend), but because my friend is also working in a company so i'm alone, since i'm still not working (waiting for my CISCO stuff). Now when i have time, i will try to share some of my knowledge, ok let's just start....
We know there are some contribution to NHibernate because this ORM is so popular, one of the contribution that i like is to let NHibernate use attribute (like DLinq and XPO) instead of xml file to map our class/domain object to the DBMS, but actually it is just some helper class that let us set some attributes to our class and then we can generate the map data.
First we just create some class that will be map with some table
class Customer
{
}
and then we add some attributes to map this class to a table
[NHibernate.Mapping.Attributes.Class(Table="Customers")]
class Customer
{
}
and the we add one or more property that represent the id/primary key of the table and the attributes that map this property as id
private String _ID;
[NHibernate.Mapping.Attributes.Id(Name="CustomerID")]
[NHibernate.Mapping.Attributes.Generator(1, Class="native")]
public String ID
{
get
{
return _ID;
}
}
and of course we should add some column/property and the attribute that map this property as column
private String _name;
[NHibernate.Mapping.Attributes.Property(NotNull=true)]
public String Name
{
get
{
return _name;
}
set
{
_name=value;
}
}
Like that...
After we have created all the mapped property we can start the code that changes all this attribute mapping to a mapping data.
This is the code...
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
NHibernate.Mapping.Attributes.HbmSerializer.Default.HbmDefaultAccess = "field.camelcase-underscore";
NHibernate.Mapping.Attributes.HbmSerializer.Default.Serialize( stream,System.Reflection.Assembly.GetExecutingAssembly() );
stream.Position = 0;
cfg.AddInputStream(stream);
stream.Close();
- First we create the NHibernate configuration and then we create a memorystream to store the map file in-memory.
- Then we set some property, with this setting NHibernate will convert the name of the property in the camel case and will add an underscore before to get the name of the field that hold this data.
- Then we serialize the class into xml (in-memory) from this assembly (executing assembly).
- And last we rewind the stream and add the stream into the configuration then finally close the stream.
So other than cfg.AddAssembly / cfg.AddClass / anything ... we can also use cfg.AddInputStream to add the stream where the map exist.
That's it... Hope it's useful...
Ciaooo !!!