It’s difficult to break away from old traditions, but sometimes it pays to think a differently. NHibernate is an awesome example of what I am talking about. It gives a developer the flexibility of concentrating on writing code instead of having to synchronize the database with the data layer/code.
Currently, what I see happening quite often is the following.
- Specification document gets drawn up.
- Database is slapped together by the developer or DB “dude”.
- Developer starts working on the code, only to realize that a column is missing due to either poor planning or requirements changing, the developer spends time having to change/add a column/s and tracking down all the changes in the stored procedure and hopefully he/she has tracked all of them down, otherwise….
I have 2 words, Fluent NHibernate…
How to setup Fluent NHibernate
- Download Fluent NHibernate from http://fluentnhibernate.org/downloads
- Add references to the DLLs
- Create your first Entity
public class Person
{
public virtual int ID { get; private set; }
public virtual string Name { get; set; }
public virtual string Lastname { get; set; }
}
public class PersonMap : ClassMap<Person>
{
public PersonMap()
{
Schema("dbo");
Table("Person");
Id(x => x.ID);
Map(x => x.Name);
Map(x => x.Lastname);
}
}
- Setup Fluent NHibernate and this is where fluent really shines. No more having to deal with the pain of the XML configuration.
public static class SessionFactory
{
public static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005
.ConnectionString(
c => c.FromConnectionStringWithKey("AthenaConnectionString")))
.Mappings(
m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
}
private static void BuildSchema(Configuration config)
{
new SchemaUpdate(config).Execute(true, true);
}
}
- How to use Fluent NHibernate in a simple example
var sessionFactory = SessionFactory.CreateSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
Person person = new Person { Name = "Pieter", Lastname = "Germishuys" };
session.SaveOrUpdate(person);
transaction.Commit();
}
}
3JDQDM2DSFR8
15a366ee-39e4-46da-877b-2f43c74fde1b|0|.0