views:

39

answers:

1

Hey,

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.Amenities.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

+1  A: 

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:

Mauricio Scheffer