Search code examples
nhibernatefluent-nhibernateautomapping

Problem Understanding Fluent nHibernate Automapping and Relationship


I am a bit new to Fluent nHibernate and ran into a scenario with my schema I'm not sure how to address.

Say I have two tables:

Track

TrackId UserId Name

Users

UserId Name

Now, what I want to do is have the ability to access the related User object by track. For example:

var track = repo.GetById(1);

var userName = track.User.Name;

How can I get nHibernate to automap this new custom User property?


Solution

  • Here you go:

    public class Track
    {
        public virtual int Id {get;set;}
        public virtual string Name {get;set;}
        public virtual User User {get;set;}
    }
    
    public class User
    {
        public virtual int Id {get;set;}
        public virtual string Name {get;set;}
    }
    
    // Usage
    var track = repo.GetById(1);
    var username = track.User.Name;
    

    More information can be found here.