代码之家  ›  专栏  ›  技术社区  ›  oillio

在Castle ActiveRecord中手动管理联接表

  •  0
  • oillio  · 技术社区  · 16 年前

        [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 回复  |  直到 16 年前
        1
  •  1
  •   Community Mohan Dere    9 年前

    当您的关系表(在您的情况下是“Join”表)具有与它相关的表的FKs以外的其他字段时,请使用 [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; }
    }