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。回复贴还有一个相关字段就是回复所属主题贴的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实体继承简单描述
网站链接:http://www.shufengxianlan.com/qtweb/news7/377607.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联