为了演示继承与关系,我们创建一个论坛数据库,在数据库中创建三个表:
1 、 论坛版块分类表 dbo.Categories:
字段名
字段类型
可空
备注
CategoryID int
CategoryName varchar(50)
2 、 论坛版块表 dbo.Boards:
not null
not null
identity/主键
字段名
BoardID
BoardName
BoardCategory
字段类型
int
varchar(50)
int
可空
not null
not null
not null
备注
identity/主键
对应论坛版块分类表
的CategoryID
3 、 论坛主题表 dbo.Topics:
字段名 字段类型
可空
备注
TopicID
TopicTitle
TopicContent
ParentTopic
int
varchar(50)
varchar(max)
int
not null
not null
not null
null
identity/主键
如果帖子是主题贴这
TopicType
实体继承的定义
tinyint
not null
个字段为null,否则
就是所属主题id
0 – 主题贴
1 – 回复帖
Linq to sql 支持实体的单表继承,也就是基类和派生类都存储在一个表中。对于论坛来
说,帖子有两种,一种是主题贴,一种是回复帖。那么,我们就先定义帖子基类:
[Table(Name = "Topics")]
public class Topic
{
[Column(Name = "TopicID", DbType = "int identity", IsPrimaryKey = true,
IsDbGenerated = true,CanBeNull = false)]
public int TopicID { get; set; }
[Column(Name = "TopicType", DbType = "tinyint", CanBeNull = false)]
public int TopicType { get; set; }
[Column(Name = "TopicTitle", DbType = "varchar(50)", CanBeNull = false)]
public string TopicTitle { get; set; }
[Column(Name = "TopicContent", DbType = "varchar(max)", CanBeNull = false)]
public string TopicContent { get; set; }
}
这些实体的定义大家应该很熟悉了。下面,我们再来定义两个实体继承帖子基类,分别
是主题贴和回复贴:
public class NewTopic : Topic
{
public NewTopic()
{
base.TopicType = 0;
}
}
public class Reply : Topic
{
public Reply()
{
base.TopicType = 1;
}
[Column(Name = "ParentTopic", DbType = "int", CanBeNull = false)]
public int ParentTopic { get; set; }
}
对于主题贴,在数据库中的TopicType就保存为0,而对于回复贴就保存为1。回复贴
还有一个相关字段就是回复所属主题贴的TopicID。那么,我们怎么告知Linq to sql 在
TopicType 为0 的时候识别为NewTopic,而1 则识别为Reply 那?只需稍微修改一下前面
的Topic 实体定义:
[Table(Name = "Topics")]
[InheritanceMapping(Code= 0, Type = typeof(NewTopic), IsDefault = true)]
[InheritanceMapping(Code= 1, Type = typeof(Reply))]
public class Topic
{
[Column(Name = "TopicID", DbType = "int identity", IsPrimaryKey = true,
IsDbGenerated = true,CanBeNull = false)]
public int TopicID { get; set; }
[Column(Name = "TopicType", DbType = "tinyint", CanBeNull = false, IsDiscriminator
= true)]
public int TopicType { get; set; }
[Column(Name = "TopicTitle", DbType = "varchar(50)", CanBeNull = false)]
public string TopicTitle { get; set; }
public string TopicContent { get; set; }
}
为类加了InheritanceMapping 特性定义,0 的时候类型就是NewTopic,1 的时候就是
Reply。并且为TopicType字段上的特性中加了IsDiscriminator = true,告知Linqto sql 这
个字段就是用于分类的字段。