Fluent Nhibernate Database configuration

Below is a quick code to connect sql database in Nhibernate using Fluent Nhibernate .

You can read more here for developing complete application.

static ISessionFactory _sessionFactory = null;
public static ISessionFactory CreateSessionFactory()
{
_sessionFactory = FluentNHibernate.Cfg.Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c
.Server(“localhost\\sqlexpress”)
.Database(“xxxx”)
.Username(“xxxxx”)
.Password(“xxxxxxxx”)))
.Mappings(m => m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.Load(“FluentNhibernateMappingSample”)))
//.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
return _sessionFactory;}

private static void BuildSchema(Configuration config)
{
new SchemaExport(config).Create(true, true);
}

public static ISession GetNHBSession()
{
if (_sessionFactory == null)
{
_sessionFactory = CreateSessionFactory();

}
return _sessionFactory.OpenSession();
}

Get List by Id’s in Nhibernate

Hello Folks ,

As we know that we do not need to write separate method to get an entity Object by Id in Nhibernate . It’s already provided by Nhibernate . Many times we have  more than one Id’s and we want to get data object for them …

Well here is a simple probably general method (if you add it to your base repository) for all of your objects (which has “Id” column)

Public IEnumerable Get(IEnumerables ids)

{

var myCriteria = Session.CreateCriteria().Add(Restrictiona.In(“Id”, ids.ToArray()));

// here you  can put your logic ..

return myCriteria.List();

}

 

Fluent Nhibernate : Create Many-to-Many Relationship table

Scenario :

I have 2 objects User and Group . One User can have many Groups and , many Groups can have many users . To implement this relation , I need a UserGroupMapping table which has reference of UserID and GroupID.

UserGroup Object

public class UserGroup    {

public UserGroup()

{

Users = new List<Users>();

}

public virtual int Id { get; set; }

public virtual string Value { get; set; }
public virtual IList<Users> Users { get; set; }

}

Users Object

public class Users    {

public Users()

{

UserGroups = new List();

}

public virtual int Id { get; set; }

public virtual string FirstName{ get; set; }

public virtual string LastName{ get; set; }
public virtual IList UserGroups { get; set; }

}


User mapping

public class UsersMap:ClassMap

{

public UsersMap()

{

Table(“Users”);

Id(x => x.Id,”UserID”).GeneratedBy.Identity();

Map(x => x.FirstName);

Map(x => x.LastName);

HasManyToMany<UserGroups>(x => x.Groups).Table(“UserGroupMapping“)

.ParentKeyColumn(“UserID”)

.ChildKeyColumn(“GroupID”);

Map(x => x.CreatedOn);

}

}

Group Mapping

public class UserGroupMap :ClassMap

{

public UserGroupMap()

{

Table(“Groups”);

Id(x => x.Id,”GroupID”).GeneratedBy.Identity();

Map(x => x.Value);

HasManyToMany<Users>(x => x.Users).Table(“UserGroupMapping“)

.ParentKeyColumn(“GroupID”)

.ChildKeyColumn(“UserID”);

References(x => x.CreatedBy).Not.LazyLoad();

Map(x => x.CreatedOn);

Map(x => x.UpdatedOn).Update();

}

}

 

Above mapping will create a table UserGroupMapping.  You can see my previous post on self reference of an object .

Nhibernate : Self reference to an object using Fluent Nhibernate

BusinessObject

Public Class Employee

{

public virtual  int Id {get; set;}

public virtual  string Name {get; set;}

public virtual  string Address {get; set;}

}
Domain Model :

Public Class Employee

{

public virtual  int Id {get; set;}

public virtual  string Name {get; set;}

public virtual  string Address {get; set;}

Public IList<Employee> Managers {get;set;}

}

Scenario :1

One employee can have more than one Manager , Manager is also an employee . Fluent Nhibernate takes care of the self-reference of the object .Here in the business model we have the many-to-many relationship.

But in this Domain Model Employee object has  self-reference .

Solution :1

Mapping :

Public class EmployeeManagermap : ClassMap

{

Public EmployeeManagermap()

{

Id(x => x.Id,”EmployeeId”);

map(x=> x.Name ,”EmployeeName”);

HasManyToMany(x => x.Managers)

.ParentKeyColumn(“EmployeeId”)

.ChildKeyColumn(“ManagerID”)

.Table(“EmployeeManagers”);

}

}


The above mapping will create a Table EmployeeManagers which will have two columns EmployeeId and ManagerId.

That’s it .

Hope this help to someone  . If you face some problem to implement any Nhibernate mapping scenario , you can contact me. 🙂


Common mistakes done while using nhibernate

I was reading  a “nhibernate in Action” and found some interesting things. I will post more  from this book once I am through .

Common mistakes done while using nhibernate

If you read this section, you may just have receive one of these performance complains we talked
about. Here are some common mistakes you may have done and tips to help dramatically improve
your application’s performance (and make the end-users happier).


By the way, you should consider writing performance tests at an early stage to avoid waiting for the
end-user to tell you that your application is too slow. And don’t forget to also optimize your database
(adding the correct indexes, etc.).

A mistake that some new NHibernate developers commit is that they create the session factory
more than required. This is a very expensive process. Most of the time, it is done once at the start of
the application. Avoid keeping the session factory at a place that lives shorter than your application
(like keeping it in a web page request).

Another common mistake, related to the fact that NHibernate makes it so easy to load entities, is
that you may load more information than you need (without even knowing it). For example,
associations and collections are fully initialized when lazy loading is not enabled. So even when
loading a single entity, you may end fetching a whole object graph. The general advice here is to
always enable lazy loading and to carefully write your queries.

Another related problem, arising when enabling lazy loading, is the n+1 select problem. For more
details, read chapter 8, section 8.6.1, “Solving the n+1 selects problem”. By the way, a nice way to
spot this issue early is to measure the number of queries executed per page; you can easily achieve
that by writing a tool to watch logs from NHibernate.SQL at DEBUG level. If it is higher than a certain
limit, you have got a problem to solve and do it immediately, before you forget what is going on in
this page.
You may also measure other performance-killer operations (like the number of remote calls
per page) and global performance information (like the time it takes to process each page).
You should also try to load the information you need using the minimal number of queries
(however, avoid expensive queries like those involving Cartesian product). Note that it is generally
more important to minimize the number of entities loaded (row count) than the number of fields
loaded for each entity (column count).

Chapter 8 describes many features that can help you writing optimized queries.
Now, let’s talk about a less known issue. This one is related to the way NHibernate works. When
you load entities, the NHibernate session keeps a number of information about them (for transparent
persistence, dirty checking, etc.). And when committing/flushing, the session uses this information to
perform the required operations.

There is a specific situation where this process can be a performance bottleneck: When you load a
lot of entities to update only few of them, this process will be slower than it should be. The reason is
that the session will check all these entities to find those that must be updated. You should help it
avoiding this waste by evicting unchanged entities or using another session to save changed entities.
As a last resort, consider using the 2nd level cache (and the query cache) to hit the database less
often and reuse previous results. Read chapter 6, section 6.3, “Caching theory and practice”, for more details on the pros and cons of this feature.

You can download this book from here

 

Nhibernate ,Fluent nhibernate and Repository Pattern works great together

As I am trying to take a deep dive in Nhibernate world since last month , I have read a lot of articles and blogs .All were very good and some of them were really helpful. Well though all the stuff i have looked over internet was for sure interesting but i hardly find any of them who can talk about a running sample application(at least i didn’t find that ). So i have decided to try to write something which is simple and you can actually see it working immediately. I hope this will help to all those folks who are making their mind to have a look at this wonderful ‘state of art’ as i call it 😉

You can get details of how to download all required details to start form here

So lets start ..

Introduction

When we start developing any business application , we talk about so many things .But i thing we never talk about how we will make our application speak with the database ???? One answer comes in  my mind for this question , if i ask it , is that “You stupid … is this your first time developing some application !!! humm..We off course will do it the same way , we are doing it since last so long time ..WRITE DATA ACCESS LAYER AND SCRIPTS“. So we really do not want to spend a lot of unnecessary time on discussing this obvious part of application.

Well when project start the UI and other modules are ready but….  We say GUYS LETS FIRST CREATE THE PROTOTYPE . Well needless to say in most of the cases, the project continues on the application created for the prototype.  Most of the time in developing an application is in writing Data Access layer and Scripts and offcourse to synch it with our so call Prototyped application.  It would be nice to have something which helps me to concentrate on writing my business application rather worrying how i will save this data in to the database..  ORM (Object Relational Model)is the answer .. Off course there are many ORM’s available on the web but i Nhibernate is one of the most popular one.

Scenario

In this sample application we will implement the very basic scenario . I have Employee and Department entities .We also have a value object Address. The difference between Entity and Value object is that , value object do not have any identity but entities have identity. Employee and Department object shares many-to-one relationship . one department can have many employees.

Repository

In this sample we are going to implement a base repository so that we do not have to write similiar methods in for all the objects. I have created an iRepository interface of generic type and implemented in a base repository. With this approach we implement the  Repository Pattern

also, in our small application .

Nhibernate mapping

Nhibernate is an ORM and we need to map object with the data context properties.Generally Nhibernate provide support to do Mapping in an XML file xx.hbm.xml. This way we decouple our mapping from the business logic and data context.We can easily change the mapping in the xml mapping file.

Why Fluent Nhibernate

Well if Nhibernate already support mapping in xml file than why we need Fluent nhibernate  for mapping. Its not mendatory to use Fluent nhibernate in your application but its really helpfull to avoid  unnecessary changes/missing mapping.We  do mapping in c# code  so that if there is any change in the mapping than we get immediately a compilation error and its easy to fix the problem . Needless to say , compiler does not compile xml  so if there is any problem in mapping , we cannot find it in compile time.. and it can really take long time some time to identify the problem.

Component mapping

In Nhibernate we have <bag> node and it has its property. Fluent  nhibernate has similiar functionality and we call it component.

i.e Employee has Address properties but  we will save it the employee table so we need to map it as component in the EmployeeMap class.  All the mapping files are inheriting ClassMap which helps Fluent Nibernate to identify the mapping files .

public EmployeeMap()

{

Id(x => x.Id);

Map(x => x.Name);

References(x => x.Department);

Component<Address>(x => x.HomeAddress,

a =>

{

a.Map(x => x.Line1, “HomeAddress_Line1”);

a.Map(x => x.Line2, “HomeAddress_Line2”);

}).LazyLoad();

Component<Address>(x => x.WorkAddress,

a =>

{

a.Map(x => x.Line1, “WorkAddress_Line1”);

a.Map(x => x.Line2, “WorkAddress_Line2”);

});

 

}

Sample Application solution structure:
References:
You can download  source code from here
Note : please change connection setting to tun the sample

Falling in love with NHibernate..

i have heard a lot about NHibernate so finally decided to have a look at it and decide it by myself.
I did some gooogling and read some of the articles about it .
Finally i have found a nice article originally written by Gabriel Schenker here

I really like the article and did the sample by myself. thought there are some bugs in the sample and i corrected them and finally i was able to test it with NUnit also.

You can download the source code form NUnit Test Here.

Update : Sample with test app can be downloaded from  Here

Read custom Properties of an Excel Workbook

You can read the Custom properties of any office document (below is an example for Excel workbook)

using System.Reflection;
using System;

object GetExcelWorkbookPropertyValue(Microsoft.Office.Interop.Excel.Workbook workbook, string propertyName)
{
object builtInProperties =workbook.CustomDocumentProperties;
Type builtInPropertiesType = builtInProperties.GetType();

object property = builtInPropertiesType.InvokeMember(“Item”, BindingFlags.GetProperty, null, builtInProperties, new object[] { propertyName });
Type propertyType = property.GetType();
object propertyValue = propertyType.InvokeMember(“Value”, BindingFlags.GetProperty, null, property, new object[] { }); return propertyValue;

}

Hope this will help you….