Linq实体继承简单描述

Linq有很多值得学习的地方,这里我们主要介绍Linq实体继承的定义,包括介绍Linq to sql支持实体的单表继承等方面。

Linq实体继承的定义

Linq to sql支持实体的单表继承,也就是基类和派生类都存储在一个表中。对于论坛来说,帖子有两种,一种是主题贴,一种是回复帖。那么,我们就先定义帖子基类:

  1. [Table(Name = "Topics")]
  2. public class Topic
  3. {
  4. [Column(Name = "TopicID", DbType = "int identity", IsPrimaryKey = true,
    IsDbGenerated = true, CanBeNull = false)]
  5. public int TopicID { get; set; }
  6. [Column(Name = "TopicType", DbType = "tinyint", CanBeNull = false)]
  7. public int TopicType { get; set; }
  8. [Column(Name = "TopicTitle", DbType = "varchar(50)", CanBeNull = false)]
  9. public string TopicTitle { get; set; }
  10. [Column(Name = "TopicContent", DbType = "varchar(max)", CanBeNull = false)]
  11. public string TopicContent { get; set; }
  12. }

这些Linq实体继承的定义大家应该很熟悉了。下面,我们再来定义两个Linq实体继承帖子基类,分别是主题贴和回复贴:

  1. public class NewTopic : Topic
  2. {
  3. public NewTopic()
  4. {
  5. base.TopicType = 0;
  6. }
  7. }
  8. public class Reply : Topic
  9. {
  10. public Reply()
  11. {
  12. base.TopicType = 1;
  13. }
  14. [Column(Name = "ParentTopic", DbType = "int", CanBeNull = false)]
  15. public int ParentTopic { get; set; }
  16. }

对于主题贴,在数据库中的TopicType就保存为0,而对于回复贴就保存为1。回复贴还有一个相关字段就是回复所属主题贴的TopicID。那么,我们怎么告知Linq to sql在TopicType为0的时候识别为NewTopic,而1则识别为Reply那?只需稍微修改一下前面的Topic实体定义:

  1. [Table(Name = "Topics")]
  2. [InheritanceMapping(Code = 0, Type = typeof(NewTopic), IsDefault = true)]
  3. [InheritanceMapping(Code = 1, Type = typeof(Reply))]
  4. public class Topic
  5. {
  6. [Column(Name = "TopicID", DbType = "int identity", IsPrimaryKey = true,
    IsDbGenerated = true, CanBeNull = false)]
  7. public int TopicID { get; set; }
  8. [Column(Name = "TopicType", DbType = "tinyint", CanBeNull = false,
    IsDiscriminator = true)]
  9. public int TopicType { get; set; }
  10. [Column(Name = "TopicTitle", DbType = "varchar(50)", CanBeNull = false)]
  11. public string TopicTitle { get; set; }
  12. [Column(Name = "TopicContent", DbType = "varchar(max)", CanBeNull = false)]
  13. public string TopicContent { get; set; }
  14. }

为类加了InheritanceMapping特性定义,0的时候类型就是NewTopic1的时候就是Reply。并且为TopicType字段上的特性中加了IsDiscriminator = true,告知Linq to sql这个字段就是用于分类的字段。

posted @ 2012-05-31 18:54  Peter.Luo  阅读(245)  评论(0)    收藏  举报