I am sure this is a straightforward question but consider the following: I have a reference between company and sector as follows:
public class Company {
pub
This is easily done with a formula property.
public class Company {
public virtual Guid Id { get; set; }
public virtual Guid? SectorId { get; set; }
public virtual Sector Sector { get; set; }
}
public class CompanyMap : ClassMap {
public CompanyMap() {
Id(x => x.Id); // Maps to a column named "Id"
References(x => x.Sector); // Maps to a column named "Sector_id", unless you change the NHibernate default mapping rules.
Map(x => x.SectorId).Formula("[Sector_id]");
}
}
This should act exactly how you want. When the Company
is new, SectorId
will be null; when Company
is fetched from the DB, SectorId
will be populated with the given formula value. The SectorId
is exposed as a property, which makes it really nice for dealing with web drop downs, etc. When you save, you'll still need to bind the "real" association. Assuming that SectorId
was selected in a form...
using (var txn = session.BeginTransaction()) {
// Set the FK reference.
company.Sector = session.Load(company.SectorId);
// Save the new record.
session.Save(company);
// Commit the transaction.
txn.Commit();
}