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

后端 未结 3 1634
不知归路
不知归路 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<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();
    }
    
    0 讨论(0)
  • 2021-02-20 16:57

    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")")?

    0 讨论(0)
  • 2021-02-20 17:06

    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

    0 讨论(0)
提交回复
热议问题