map composite keys in Nhibernate

I have a legacy database where 2 columns are used in all the table create composite keys .

One of he error message which you may see :

must have same number of columns as the referenced primary key nhibernate

Solution :

Table1

ProjectID Version Project Name

Table 2

ProjectID Version Table2ID Name1

Table 3

ProjectID Version Table2ID Table3ID Name2

I have a common Composite key Project ID and Version from Table 1.




Mapping will look like this 



that’s it Smile


 


				
Advertisements

Nhibernate error :Incorrect syntax near the keyword ‘Function’.

In our database sometimes we have column names which are actually the database keywords . If we want to access such columns from Nhibernate session  , it throws error message “Incorrect syntax near the word :’SOME DB KEYWORD’

 

Mapping :Before :

Mapping :After

Keeping database base reserve keyword in “[ ]”  brackets will fix the error message.

 

You can have look on all my previous Nhibernate posts

 

 

 

 

 

 

 

 

 

 

 

User Nhibernate with Legacy database

Topday we will talk little bit more about the Nhibernate topic. If you are new to this topic than

you can have look at  previous post

As its well accepted that Nhibernate is getting really (probably) first choice in applcation development
Its really easy to stary with Nhibernate for a new application development. You have more control
on your application  code and its db realtions .
Well  this doesnt go as smooth with Legacy DB as new application.

I have legacy database and it has many relations which could drive tyou crazy like anything .

Here in this post I will present a quick but very useful ways to map you WIERED realtions in Nhibernate using fluent Nhibernate.

Here is my small datamodel to explain this kinda of mapping

Data model

Mapping

 

Above mapping will create a mapping for the ToolLangTbl.

IF you notice int he mapping we have used CompositId to map such mappings.

Note :

In such cases always implement GetHashCode and Equal methods as below

 

 

If you still have some other wiered database relations and need help to map them ..I can try to help you in it.

Have a nice day ahead !!

 

 

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();
}

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 .

Let Fluent-Nhibernate handle Nhibernate mapping..

In my previous post I have talk about Nhibernate and NHibernate Mapping.  As i have already realized the power of Nhibernate , and  I have dug it down  more and more . Will everything works like charm but I personally found to create mapping file for all the entities/object.  So I have decided to look for some  more relevent solution so that  I really can avoid this mapping step while working on my appplicaiton.

Fluent Nhibernet is the answer of my problem .Fluent nhibernate is an auto mapper which create mapping of your objects with the database table columns. We really do not have to worry about the mapping now and we can concentrate more on writing better application. You can download Fluent Nhibernate from here . I am also attaching sample business model to use Fluent Nhibernate . You can download  code form here .

 

You need to reference some libraries as below .

using FluentNHibernate;

using NHibernate;

using FluentNHibernate.Cfg;

using FluentNHibernate.Cfg.Db;

using FluentNHibernate.Automapping;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Criterion;

 

 

 

I have wrapped the use of Nhibernate in Repository . It really adds more power and flexibility to the application when Nhibernate is used with Repository pattern.

Note that i have used the namespace “FluentNhibernateSampleORM.Model” Now Fluent Nhibernate will pick up all the objects under this namespace automatically and map it to the database .

Reference: http://wiki.fluentnhibernate.org/Getting_started