Castle ActiveRecord实现one–one关系的映射
一.编写实体类代码为了实现多对多的关系,我们要在Customer 、CustomerAddress
类中分别使用OneToOne特性。示例代码:
Customer 类:
- [ActiveRecord("Customer")]
- public class Customer : ActiveRecordBase<Customer>
- {
- private Guid custID;
- private string name;
- private CustomerAddress addr;
- [PrimaryKey]
- public Guid CustomerID
- {
- get { return custID; }
- set { custID = value; }
- }
- [OneToOne(Cascade=CascadeEnum.All)]
- public CustomerAddress CustomerAddress
- {
- get { return addr; }
- set { addr = value; }
- }
- [Property]
- public string Name
- {
- get { return name; }
- set { name = value; }
- }
- }
CustomerAddress 类:
- [ActiveRecord("CustomerAddress")]
- public class CustomerAddress : ActiveRecordBase<CustomerAddress>
- {
- private Guid custID;
- private string address;
- private Customer cust;
- [PrimaryKey(PrimaryKeyType.Foreign)]
- public Guid CustomerID
- {
- get { return custID; }
- set { custID = value; }
- }
- [OneToOne]
- public Customer Customer
- {
- get { return cust; }
- set { cust = value; }
- }
- [Property]
- public string Address
- {
- get { return address; }
- set { address = value; }
- }
- }
二.初始化数据库
根据实体类来逆向的创建数据库的表(数据库要是已存在的)
- IConfigurationSource source = System.Configuration.ConfigurationManager.GetSection("activerecord") as IConfigurationSource;
- ActiveRecordStarter.Initialize(source, typeof(Customer), typeof(CustomerAddress));
- ActiveRecordStarter.CreateSchema();//初始化数据库
三.编写测试代码
1.级联增加
- /// <summary>
- /// 添加数据
- /// </summary>
- private static void AddSouces()
- {
- //使用事务处理
- using (TransactionScope tran = new TransactionScope())
- {
- try
- {
- Customer cust = new Customer();
- cust.CustomerID = new Guid();
- cust.Name = "张三";
- CustomerAddress custAddress = new CustomerAddress();
- custAddress.Address = "address";
- //支出对应关系
- cust.CustomerAddress = custAddress;
- custAddress.Customer = cust;
- custAddress.Save(); //保存Customer对象
- tran.VoteCommit(); //执行事务
- }
- catch (Exception)
- {
- tran.VoteRollBack(); //若出现异常,回滚事务
- }
- }
- }
2级联删除:因为我们有设置Cascade=CascadeEnum.All,删除一个Customer,对应的CustomerAddress 记录也会删除
- SimpleQuery<Customer> query = new SimpleQuery<Customer>(typeof(Customer), "From Customer as n where n.Name = ?", "李四");
- Customer cust = query.Execute().FirstOrDefault();
- cust.Delete();//级联删除,CustomerAddress表的相应数据也会删除