1

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...

J. Ed
  • 6,692
  • 4
  • 39
  • 55

1 Answers1

0

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");
        });
    });
});
NOtherDev
  • 9,542
  • 2
  • 36
  • 47
  • `c` is of type `IColumnMapper` which doesn't define a `ForeignKey` function. Any other ideas? – J. Ed Apr 01 '12 at 08:19
  • Well, you're right. So it seems there's no way to define foreign keys names for composite keys. But why do you care, you've said that your database is legacy and can't be changed and `ForeignKey` is needed only to set up foreign key name in case of schema export, which you don't do. – NOtherDev Apr 01 '12 at 08:53
  • oh, so there's something fundamentally missing in my understanding of mapping by code: how do I tell NHib which column in `UsersAddresses` references which column in `Users`? (i.e `username -> username_fk` etc.) – J. Ed Apr 01 '12 at 09:33
  • I think the order matters. If you've defined username & email properties as a composite key in `Users`, you should have the same order of columns definitions in key's `Columns` method. – NOtherDev Apr 01 '12 at 10:06