Welcome

首页 / 软件开发 / .NET编程技术 / Castle ActiveRecord学习实践(5) 实现Many–Many关系的映射

Castle ActiveRecord学习实践(5) 实现Many–Many关系的映射2011-02-03 cnblogs terrylee主要内容

1.准备数据库表

2.编写实体类

3.编写测试代码

一.准备数据库表

接着在上篇文章中的例子,为了实现多对多的关系,我们引入Community,即每个Blog可以属于多个社区,每个社区也可以有多个Blog。

CREATE TABLE Blogs (
blog_id int IDENTITY(1, 1) PRIMARY KEY,
blog_name varchar(50),
blog_author varchar(50)


CREATE TABLE Blog_Community (
blog_Id int NOT NULL ,
community_Id int NOT NULL


CREATE TABLE Communities (
community_Id int IDENTITY (1, 1) PRIMARY KEY,
community_Name varchar (50) ,
community_Intro varchar (500)

二.编写实体类代码

为了实现多对多的关系,我们要在Blog、Community类中分别使用HasAndBelongsToMany特性,不需要编写Blog_Community类。示例代码:

// Blog
[HasAndBelongsToMany( typeof(Community),
Table="Blog_Community",
ColumnRef=" community_id ",
ColumnKey=" blog_id " )]
public IList Communitys
{
get { return _community; }
set { _ community = value; }
}

// Community
[HasAndBelongsToMany( typeof(Blog),
Table="Blog_Community",
ColumnRef="blog_id",
ColumnKey="community_id" )]
public IList Blogs
{
get { return _blog; }
set { _ blog = value; }
}