How to Create a Foreign Key Relation in Fluent NHibernate

If you dont want to use a generator for your nhibernate classes when you create a new foreign key, here is a simple guide to create a new one-to-many relation in NHibernate:

Assume that you want to associate your user class to item class. User can have multiple items and one item cannot be owned by multiple users:

In your user map class:

            HasMany(x => x.item).KeyColumn("idUser");

Your user table has a column named idItem which references identity column of Item table.

In your item class:
        public virtual IList item{ get; set; }

It is vital to use Interface here, otherwise you will get a lazyLoad Exception.

In your user class constructor:
        item= new List();

In your item map class:
        References(x => x.user).Column("idUser");
In your item class:
        public virtual user user{ get; set; }

Noe if you want to access owner of an item, you can just call this.user. If you want to access owner in out the scope of the nhibernate session, you need to use Not.LazyLoad() in your corresponding mapping.

For more information about lazyLoading, have a look at my post about this topic.

No comments:

Post a Comment