在向大家详细介绍Linq实体继承使用之前,首先让大家了解下Linq to sql是否能根据TopicType识别派生类,然后全面介绍Linq实体继承使用。
Linq实体继承使用
定义好实体继承之后,我们就可以Linq实体继承使用了。先是自定义一个DataContext吧:
- public partial class BBSContext : DataContext
- {
- public Table<BoardCategory> BoardCategories;
- public Table<Board> Boards;
- public Table<Topic> Topics;
- public BBSContext(string connection) : base(connection) { }
- }
然后,我们来测试一下Linq to sql是否能根据TopicType识别派生类:
- BBSContext ctx = new BBSContext("server=xxx;database=BBS;uid=xxx;pwd=xxx");
- var query = from t in ctx.Topics select t;
- foreach (Topic topic in query)
- {
- if (topic is NewTopic)
- {
- NewTopic newtopic = topic as NewTopic;
- Response.Write("标题:" + newtopic.TopicTitle + " 类型:" +
newtopic.TopicType + "<br/>"); - }
- else if (topic is Reply)
- {
- Reply reply = topic as Reply;
- Response.Write("标题:" + reply.TopicTitle + " 类型:" +
reply.TopicType + " 隶属主题:" + reply.ParentTopic + "<br/>"); - }
- }
然后我们往Topics表中加一些数据,如下图:
启动程序得到如下测试结果:
再来看看如何进行增删操作
- NewTopic nt = new NewTopic() { TopicTitle = "还是新主题",
TopicContent = "还是新主题" }; - Reply rpl = new Reply() { TopicTitle = "还是新回复",
TopicContent = "还是新回复", ParentTopic = 4 }; - ctx.Topics.Add(nt);
- ctx.Topics.Add(rpl);
- ctx.SubmitChanges();
- rpl = ctx.Topics.OfType<Reply>().Single(reply => reply.TopicID == 8);
- ctx.Topics.Remove(rpl);
- ctx.SubmitChanges();
以上介绍Linq实体继承使用