Castle ActiveRecord HasAndBelongsToMany问题

时间:2010-06-19 17:07:17

标签: nhibernate castle-activerecord

我正在使用monorail / activerecord,并且想知道当多对多表中除了2个外键之外还有一个值时,如何处理多对多关系中的项目。

例如,Business和Amenity类具有多对多的关系,因此有一个BusinessAmenity表。如果BusinessAmenity表只有外键BusinessId和AmenityId,那么你可以这样做:

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

然后添加如下关联:

business.Amenities.Add(amenity;

但是,如果BusinessAmenity类有另一个名为“Value”的列需要为每个关联设置,该怎么办?您不能再向Business.Amenities添加Amenity对象,因为您需要能够在BusinessAmenity中设置Value属性。

有人可以提供一些有关如何在ActiveRecord中执行此操作的信息吗?

谢谢! 贾斯汀

1 个答案:

答案 0 :(得分:2)

将BusinessAmenity映射到自己的BusinessAmenity类,例如(伪代码):

[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;}
}

在stackoverflow上已多次讨论过这个问题: