开发者

Castle ActiveRecord HasAndBelongsToMany issue

开发者 https://www.devze.com 2023-01-04 05:38 出处:网络
I\'m using monorail/activerecord and was wondering how you handle adding items in a many to many relationship when the many to many table has a value in it besides just the 2 foreign keys.

I'm using monorail/activerecord and was wondering how you handle adding items in a many to many relationship when the many to many table has a value in it besides just the 2 foreign keys.

For example, Business and Amenity classes have a many to many relationship so there is a BusinessAmenity table. If the BusinessAmenity table only had the foreign keys BusinessId and AmenityId then you could do this:

[HasAndBelongsToMany(typeof(Amenity),
          Table = "BusinessAmenity", ColumnKey = "businessid", ColumnRef = "amenityid", Cascade = ManyRelationCascadeEnum.None, Lazy=true)]
        public IList<Amenity> Amenities
        {
            get { return _amenities; }
            set { _amenities = value; }
        }

And then add the associations like this:

business.Ameniti开发者_如何学Ces.Add(amenity;

However, what if the BusinessAmenity class has another column called "Value" that needs to be set for each association? You can no longer add an Amenity object to Business.Amenities because what you need to be able to set the Value property in BusinessAmenity.

Can someone provide some insight into how you do this in ActiveRecord?

Thanks! Justin


Map the BusinessAmenity to its own BusinessAmenity class, e.g (pseudocode):

[ActiveRecord]
class Business {
    [PrimaryKey] int Id {get;set;}
    [HasMany] ISet<BusinessAmenity> Amenities {get;set;}
}

[ActiveRecord]    
class Amenity {
    [PrimaryKey] int Id {get;set;}
    [HasMany] ISet<BusinessAmenity> Businesses {get;set;}
}

[ActiveRecord]    
class BusinessAmenity {
    [BelongsTo] Amenity Amenity {get;set;}
    [BelongsTo] Business Business {get;set;}
    [Property] int Value {get;set;}
}

This has been discussed many times on stackoverflow:

  • nhibernate many-to-many mapping - additional column in the mapping table?
  • additional fields in NHibernate many-to-many relation tables
  • Many-to-many mapping with extra columns in join table
  • NHibernate: Many-to-many relationship with field in the relationship table
  • Using Additional Data on Intermediate Table with NHibernate
0

精彩评论

暂无评论...
验证码 换一张
取 消