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

﹥>﹥吖頭↗ 提交于 2019-12-04 02:45:12

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<Company> {
  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<Sector>(company.SectorId);
  // Save the new record.
  session.Save(company);
  // Commit the transaction.
  txn.Commit();
}

Two thoughts: First of all, wouldn't something like this accomplish what you want?

public class Company {
    public Guid ID { get; set; }
    public Sector Sector { get; set; }
    public Guid SectorID {
        get { return Section.ID; }
        // Really not sure what behavior your setter should have here; Maybe it shouldn't even have one?
        set { Sector = new Sector { ID = value }; }
    }
}

Second, when you say that the mapping created a column in the DB called Sector_Id, is that in addition to a column that you created named SectorID? If so, you can change the column name so it uses the correct name (here's the documentation for mappings, see a few headings down "Specifying the column name").

Also, are you mapping the SectorID property (eg. "Map(x => x.SectorID, "Sector_Id")")?

Steve you don't need ForeignKey property in POCO class.

For example if you will try to get id of article author no join select will be performed.

var authorID = Article.Author.ID

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!