这篇学习笔记主要介绍ActiveRecord如何处理one-to-many的映射,对于many-to-one映射只需把one-to-many的处理过程反过来就可以了。本文涉及了两个实体类User、Address,两个类的关系是一对多,下面是这两个类的实体关系图:
主要内容:
1.编写数据库
2.HasMany和BelongsTo属性说明
3.编写实体类
4.编写表示层调用代码
一、编写数据库
--
User类对应的数据表
Create Table [ Users ]
(
[ ID ] Int Identity ( 1 , 1 ) Primary Key ,
[ LoginName ] Varchar ( 50 ) not null ,
[ Password ] Varchar ( 20 ) not null
)
-- Address类对应的数据表
Create Table [ Address ]
(
ID int identity ( 1 , 1 ) primary key ,
Province Varchar ( 50 ),
City Varchar ( 50 ),
uID int FOREIGN KEY REFERENCES Users (ID)
)
Create Table [ Users ]
(
[ ID ] Int Identity ( 1 , 1 ) Primary Key ,
[ LoginName ] Varchar ( 50 ) not null ,
[ Password ] Varchar ( 20 ) not null
)
-- Address类对应的数据表
Create Table [ Address ]
(
ID int identity ( 1 , 1 ) primary key ,
Province Varchar ( 50 ),
City Varchar ( 50 ),
uID int FOREIGN KEY REFERENCES Users (ID)
)
二、HasMany和BelongsTo属性说明
HasMany属性:此属性用于代替NHibernate配置文件中的<many-to-one>标签;该属性用在“一”的类中(父对象,本文为User类),指出与“多”的类(级联对象,本文为Address类)的对应关系。具有以下几个主要子属性:
1.Type:指出关联对象的类名,相当于<many-to-one>标签中的class属性;
2.Table:指出关联对象的类对应的数据表(本文的数据表Address);
3.ColumnKey:指出关联对象对应的数据表中指向主类数据表的字段名(本文数据表Address中的字段uID);
4.Cascade:指明哪些操作会从父对象级联到关联的对象,相当于<many-to-one>标签中的cascade 属性。该属性值应为CascadeEnum枚举值之一:
a).All:表示父对象的任何操作都会关联到级联对象;
b).Delete:表示只有对父对象进行删除操作时才会关联到级联对象;
c).SaveUpdate:表示只有对父对象进行保存、更新操作时才会关联到级联对象;
d).None(默认值):表示对父对象的任何操作都不会关联到级联对象;
5.Lazy:指出是否延迟加载级联对象,其属性值为true或false,二者选一;
6.Where:指定一个附加SQL的Where子句,这里应该写HQL语句;
7.OrderBy:指定排序方式,这里应该写HQL语句;
8.Inverse:指定父对象是否级联到子对象;
BelongsTo属性:此属性用于代替NHibernate配置文件中表示<map>、<set>、<list>、<bag>之类的标签;该属性用在父对象中,指出与级联对象的对应关系。具有以下几个主要子属性:
1.Cascad:指出是否级联操作,其值于HasMany属性中的Cascade属性一样;
2.Column:指出数据表中指向父对象数据表的字段名;
3.Insert:是否允许插入;
4.Update:是否允许更新;
5.OuterJoin:是否允许外联抓取,相当于<many-to-one>标签中的outerjoin属性,其值应为OuterJoinEnum枚举值之一:
a).Auto(默认值):使用外连接抓取关联(对象),如果被关联的对象没有代理(proxy) ;
b).True:一直使用外连接来抓取关联;
c).False:永远不使用外连接来抓取关联;
三、编写类体类
1.编写实体类:User:
/**/
///jailusd@hotmail.com
///2006-09-11
/**/ /*数据库脚本
Create Table [Users]
(
[ID] Int Identity(1,1) Primary Key,
[LoginName] Varchar(50) not null,
[Password] Varchar(20) not null
)
*/
using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
using System.Collections;
namespace OneToMany
{
[ActiveRecord("Users")]
public class User : ActiveRecordBase
{
private int intID;
private string strName;
private string strPassword;
private IList AddressList = new ArrayList();
[PrimaryKey(PrimaryKeyType.Identity, "ID")]
public int Id
{
get { return intID; }
set { intID = value; }
}
[Property("LoginName")]
public string Name
{
get { return strName; }
set { strName = value; }
}
[Property]
public string Password
{
get { return strPassword; }
set { strPassword = value; }
}
[HasMany(typeof(Address), Table = "Address", ColumnKey = "uID")]
public IList Address
{
get
{
return AddressList;
}
set
{
AddressList = value;
}
}
}
}
///2006-09-11
/**/ /*数据库脚本
Create Table [Users]
(
[ID] Int Identity(1,1) Primary Key,
[LoginName] Varchar(50) not null,
[Password] Varchar(20) not null
)
*/
using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
using System.Collections;
namespace OneToMany
{
[ActiveRecord("Users")]
public class User : ActiveRecordBase
{
private int intID;
private string strName;
private string strPassword;
private IList AddressList = new ArrayList();
[PrimaryKey(PrimaryKeyType.Identity, "ID")]
public int Id
{
get { return intID; }
set { intID = value; }
}
[Property("LoginName")]
public string Name
{
get { return strName; }
set { strName = value; }
}
[Property]
public string Password
{
get { return strPassword; }
set { strPassword = value; }
}
[HasMany(typeof(Address), Table = "Address", ColumnKey = "uID")]
public IList Address
{
get
{
return AddressList;
}
set
{
AddressList = value;
}
}
}
}
2.编写实体类:Address
/**/
///jailusd@hotmail.com
///2006-09-11
/**/ /*数据库脚本
Create Table [Address]
(
ID int identity(1,1) primary key,
Province Varchar(50),
City Varchar(50),
uID int FOREIGN KEY REFERENCES Users (ID)
)
*/
using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
namespace OneToMany
{
[ActiveRecord("Address")]
public class Address :ActiveRecordBase
{
private int intID;
private string strProvince;
private string strCity;
private User objUser;
[PrimaryKey(PrimaryKeyType.Native,"ID")]
public int Id
{
get
{
return intID;
}
set
{
intID = value;
}
}
/**//// <summary>
/// 省
/// </summary>
[Property]
public string Province
{
get
{
return strProvince;
}
set
{
strProvince = value;
}
}
/**//// <summary>
/// 城市
/// </summary>
[Property]
public string City
{
get
{
return strCity;
}
set
{
strCity = value;
}
}
[BelongsTo("uId")]
public User User
{
get
{
if (objUser == null)
{
objUser = new User();
}
return objUser;
}
set
{
objUser = value;
}
}
}
}
///2006-09-11
/**/ /*数据库脚本
Create Table [Address]
(
ID int identity(1,1) primary key,
Province Varchar(50),
City Varchar(50),
uID int FOREIGN KEY REFERENCES Users (ID)
)
*/
using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
namespace OneToMany
{
[ActiveRecord("Address")]
public class Address :ActiveRecordBase
{
private int intID;
private string strProvince;
private string strCity;
private User objUser;
[PrimaryKey(PrimaryKeyType.Native,"ID")]
public int Id
{
get
{
return intID;
}
set
{
intID = value;
}
}
/**//// <summary>
/// 省
/// </summary>
[Property]
public string Province
{
get
{
return strProvince;
}
set
{
strProvince = value;
}
}
/**//// <summary>
/// 城市
/// </summary>
[Property]
public string City
{
get
{
return strCity;
}
set
{
strCity = value;
}
}
[BelongsTo("uId")]
public User User
{
get
{
if (objUser == null)
{
objUser = new User();
}
return objUser;
}
set
{
objUser = value;
}
}
}
}
3.编写配置文件(与以前一样)
四、编写表示层调用代码(只列举新增的代码)
private
void
btnAddNewUser_Click(
object
sender, EventArgs e)
{
IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource;
ActiveRecordStarter.Initialize(source, typeof(User), typeof(Address));
//使用事务处理
using (TransactionScope tran = new TransactionScope())
{
try
{
User objUser = new User();
objUser.Name = "jailu";
objUser.Password = "123456789";
objUser.Save();
Address objAddress;
for (int i = 0; i < 5; i++)
{
objAddress = new Address();
objAddress.Province = "Province" + i.ToString();
objAddress.City = "City" + i.ToString();
objAddress.User = objUser;
objAddress.Save();
}
tran.VoteCommit(); //执行事务
MessageBox.Show("Success!");
}
catch (Exception ex)
{
tran.VoteRollBack(); //若出现异常,回滚事务
MessageBox.Show("Fail!" + ex.Message);
}
}
}
{
IConfigurationSource source = System.Configuration.ConfigurationSettings.GetConfig("activerecord") as IConfigurationSource;
ActiveRecordStarter.Initialize(source, typeof(User), typeof(Address));
//使用事务处理
using (TransactionScope tran = new TransactionScope())
{
try
{
User objUser = new User();
objUser.Name = "jailu";
objUser.Password = "123456789";
objUser.Save();
Address objAddress;
for (int i = 0; i < 5; i++)
{
objAddress = new Address();
objAddress.Province = "Province" + i.ToString();
objAddress.City = "City" + i.ToString();
objAddress.User = objUser;
objAddress.Save();
}
tran.VoteCommit(); //执行事务
MessageBox.Show("Success!");
}
catch (Exception ex)
{
tran.VoteRollBack(); //若出现异常,回滚事务
MessageBox.Show("Fail!" + ex.Message);
}
}
}