One to Many mapping with an intermediate table

前端 未结 2 1192
不知归路
不知归路 2021-01-15 23:06

I thought I had this one pegged by mapping the intermediary table as a HasMany and between intermediary and child as HasOne, however HasOne expects to share a key. (No Inver

相关标签:
2条回答
  • 2021-01-15 23:41

    Why won't you make one-to-many from address to customer? Customer will contain foreign key then and address entity could be referened by other entity. In this case, you simply make References(x => x.Address); on customer table.
    When I was trying to create one-to-one relation using FluentNHibernate, I faced common problems too. If you want to leave DB structure as you showed, I guess you should try the following mapping (with adding corresponding entity fields):

     public AddressMap()
     {
        Schema("dbo");
        Table("Address");
        Id(x => x.AddressId);
        Map(x => x.AddressType);
        HasOne(x => x.CustomerAddress).Cascade.All();
     }
     public CustomerAddressMap()
     {
         Schema("dbo");
         Table("CustomerAddress");
         Id(x => x.CustomerAddressId);
         Map(x => x.FromDate)
             .Not.Nullable();
         Map(x => x.ToDate);
         HasOne(x => x.Address)
         .Constrained()
         .ForeignKey();
     }
    

    Such mapping left in my case one side empty, so I modified property setter for child entity (CustomerAddress):

    public virtual Address Address
    { 
        get { return _address; }
        set 
        {
            _address = value;
            value.CustomerAddress = this;
        }
    }
    

    After these actions one-to-one worked fine) Hope it will help you to solve the problem.

    0 讨论(0)
  • 2021-01-15 23:50

    map it as normal references

    public class CustomerAddressMap : ClassMap<CustomerAddress>
    {
        public CustomerAddressMap()
        {
            Table("CustomerAddress");
    
            Id(x => x.CustomerAddressId);
            Map(x => x.FromDate).Not.Nullable();
            Map(x => x.ToDate);
            References(x => x.Customer, "CustomerId");
            References(x => x.Address, "AddressId");
        }
    }
    
    0 讨论(0)
提交回复
热议问题