您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關Linq如何定義實體繼承的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
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。回復貼還有一個相關字段就是回復所屬主題貼的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這個字段就是用于分類的字段。
感謝各位的閱讀!關于“Linq如何定義實體繼承”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。