Linq實體繼承簡單描述
Linq有很多值得學習的地方,這里我們主要介紹Linq實體繼承的定義,包括介紹Linq to sql支持實體的單表繼承等方面。
Linq實體繼承的定義
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; }
- }
這些Linq實體繼承的定義大家應該很熟悉了。下面,我們再來定義兩個Linq實體繼承帖子基類,分別是主題貼和回復貼:
- 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?;貜唾N還有一個相關字段就是回復所屬主題貼的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; }
- [Column(Name = "TopicContent", DbType = "varchar(max)", CanBeNull = false)]
- public string TopicContent { get; set; }
- }
為類加了InheritanceMapping特性定義,0的時候類型就是NewTopic,1的時候就是Reply。并且為TopicType字段上的特性中加了IsDiscriminator = true,告知Linq to sql這個字段就是用于分類的字段。
【編輯推薦】