手动管理Castle ActiveRecord中的连接表

时间:2010-10-20 05:08:09

标签: nhibernate castle-activerecord

我有两个连接类,如下所示:

    [ActiveRecord]
    public class Store : ActiveRecordBase<Store> {
        [PrimaryKey]
        public int ID { get; set; }

        [HasAndBelongsToMany(Table = "StoreCustJoin",
                             ColumnKey = "storeID",
                             ColumnRef = "customerID")]
        public IList<Customer> customers { get; set; }
    }

    [ActiveRecord]
    public class Customer : ActiveRecordBase<Customer> {
        [PrimaryKey]
        public int ID { get; set; }

        [HasAndBelongsToMany(Table = "Join",
                             ColumnKey = "customerID",
                             ColumnRef = "storeID",
                             inverse = true)]
        public IList<Store> stores { get; set; }
    }

    [ActiveRecord]
    public class Join : ActiveRecordBase<Join> {
        [PrimaryKey]
        public int ID { get; set; }

        [BelongsTo("storeID")]
        public Store store { get; set; }

        [BelongsTo("customerID")]
        public Customer customer { get; set; }

        [Property]
        public int Status { get; set; }
    }

当我将商店连接到客户时,我也需要设置状态。所以我试着这样做:

    public void SetLink(Store theStore, Customer theCustomer, int status) {
        var link = new Join()
                       {
                           Status = status,
                           store = theStore,
                           customer = theCustomer
                       };
        theStore.customers.Add(theCustomer);
        theCustomer.stores.Add(theStore);
    }

这在ABJoin中创建两个条目,第一个具有状态集,第二个没有。如果我不将对象添加到各自的列表中,则可以正常工作。但是,在关闭当前会话并从数据库重新下载实例之前,链接不会反映在这些对象中。

那么,有没有一种方法可以在创建链接时设置状态,同时保持当前对象的有效性和最新状态?

1 个答案:

答案 0 :(得分:1)

如果您的关系表(在您的情况下为“加入”表)除了与其相关的表格的FK之外还有其他字段,请使用[HasMany]代替[HasAndBelongsToMany],即:

[ActiveRecord]
public class Store : ActiveRecordBase<Store> {
    [PrimaryKey]
    public int ID { get; set; }

    [HasMany]
    public IList<Join> customers { get; set; }
}

[ActiveRecord]
public class Customer : ActiveRecordBase<Customer> {
    [PrimaryKey]
    public int ID { get; set; }

    [HasMany]
    public IList<Join> stores { get; set; }
}

类似的问题: