Search code examples
c#nhibernatehibernate-mapping

Two FKs as one PK in NHibernate-Mapping?


My database looks like this

 Role                      Role_AppUser              AppUser
 -------------             -------------             -------------
 |Id         | <-PK        |Id         | <-FK        |UserId     | <-PK
 |Name       |             |UserId     | <-FK        |PreName    |
 |Description|             |xy         |             |SurName    |        
 -------------             -------------             -------------

Now I want those 2 FKs of Role_Appuser table to become a combined PK. How can I do this with my NHibernate mapping? I'm using mapping-by-code.

Thanks in advance.


Solution

  • In the mapping you can use a CompositeId:

    public class Role_AppUserMap : ClassMap<Role_AppUser>
    {
       public Role_AppUserMap()
       {
           Table("Role_AppUser")
           CompositeId()
             .KeyProperty(x=>x.RoleId, "Id")
             .KeyProperty(x=>x.UserId, "UserId");
       }
    }