Search code examples
nhibernatenhibernate-mapping

NHibernate: map multiple columns into a single collection


Suppose I have a table:

 ID(pk) | HOME_EMAIL | WORK_EMAIL | OTHER_EMAIL
-------------------------------------------------

and the .NET classes

class A {
    int id;
    List<MyEmail> emails;
}

class MyEmail {
    string email;
}

I suppose there's no way to map those (multiple) columns into a single collection in NHibernate, or is there? :)

It's come to a point that we'd rather not tinker with the database schema anymore so we can't do much with the database, if that helps.


Solution

  • I would suggest working with Interfaces so you could do something like this

     interface IUser
    {
        int Id {get; set;}
        IEnumerable<string> Emails {get;}
    }
    
    class MyUser : IUser
    {
        public int Id {get; set;}
        public IEnumerable<string> Emails
        {
            get
            {
                return new [] { SomeEmail, SomeOtherEmail };
            }
        }
    
        public string SomeEmail { get; set; }
        public string SomeOtherEmail { get; set; }
    }
    

    Your application can expect an IUser and not care where we got the list of emails. You would map MyUser in NH, while the application does not (and should not) care about the actual implementation.