Search code examples
nhibernatenhibernate-mappingnhibernate-mapping-by-code

nHib 3.2 mapping by code join on composite key


My (legacy, can't be changed) schema has a one-to-one relationship between User and UserAddress, with a composite key:

Users:
- username (PK)
- email (PK)
- firsname
- lastname

UsersAddresses:
- username (PK, FK)
- email (PK, FK)
- city
- street

My original idea was to use a <join to bring them all to the same class:

public class UserDTO
    {
        public string Username { get; set; }
        public string Email { get; set; }

        public string FirstName { get; set; }
        public string City { get; set; }
        //etc...

    }

but I don't know about the mapping:

Join("UsersAddresses", j=>
                {
                    j.Table("UsersAddresses");
                    j.Fetch(FetchKind.Join);
                    j.Optional(false);
                    j.Key(k=>
                            {
                    //What here???                                          
                    k.Column(c=>
                        {
                            c.Name("");
                            c.Name("");
                        });
                    k.ForeignKey("");
                    k.ForeignKey("");
                });

                                });

Is there a way to achieve this? Or perhaps I should opt for a component or a one-to-one mapping...


Solution

  • Try with Columns instead of Column - it takes any number of column mapping lambdas to allow mapping objects spanning multiple columns, like your key:

    Join("UsersAddresses", j =>
    {
        j.Table("UsersAddresses");
        j.Fetch(FetchKind.Join);
        j.Optional(false);
        j.Key(k =>
        {
            k.Columns(c =>
            {
                c.Name("username");
                c.ForeignKey("username_fk");
            }, c =>
            {
                c.Name("email");
                c.ForeignKey("email_fk");
            });
        });
    });