Search code examples
c#nhibernatefluent-nhibernatedatabase-migrationfluent-nhibernate-mapping

Fluent nHibernate reference by Id (not by object)


I have a class User, which is in the core module of the system:

public class User
{
    public virtual int Id {get; set;}
    public virtual string Name {get; set; }
}

I have also a class Company, which is in another module of the system and doesn't have a reference to the core module:

public class Company
{
    public virtual int Id {get; set;}
    public virtual string Name {get; set; }
    public virtual int OwnerUserId {get; set;}
}

How can I create a mapping of Company.OwnerUserId to be a foreign key to User.Id in database? Again, note: this mapping cannot have a reference to "User" class.


Solution

  • This is a workaround, im not sure how the schema update will generate the foreign key without mapping reference to get the metadata.

    You can create a new entity mapped to the same table:

    public class LocalUser
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
    }
    
    public class Company
    {
        public virtual int Id { get; set; }
        public virtual string Name { get; set; }
        public virtual LocalUser OwnerUserId { get; set; }
    }
    
    public class LocalUserMap : ClassMap<LocalUser>
    {
        public LocalUserMap()
        {
            Table("[User]");
            Id(x => x.Id).GeneratedBy.Identity();
            Map(x => x.Name);
        }
    }