Fluent NHibernate - How to map the foreign key column as a property

后端 未结 3 1635
不知归路
不知归路 2021-02-20 16:38

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         


        
3条回答
  •  一向
    一向 (楼主)
    2021-02-20 16:54

    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();
    }
    

提交回复
热议问题