本文主要是介绍Linq to sql:实体继承的使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
定义好继承的实体之后,我们就可以使用了。先是自定义一个DataContext吧:
public partial class BBSContext : DataContext
{
public Table<BoardCategory> BoardCategories;
public Table<Board> Boards;
public Table<Topic> Topics;
public BBSContext(string connection) : base(connection){ }
}
然后,我们来测试一下Linqto 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 inquery)
{
if (topic is NewTopic)
{
NewTopic newtopic = topic as NewTopic;
Response.Write("标题:" +newtopic.TopicTitle + " 类型:" +
newtopic.TopicType + "<br/>");
}
else if (topic is Reply)
{
Reply reply = topic asReply;
Response.Write("标题:" +reply.TopicTitle + " 类型:" +reply.TopicType
+ " 隶属主题:" + reply.ParentTopic + "<br/>");
}
}
然后我们往Topics 表中加一些数据
启动程序得到如下测试结果:
当然,你也可以在查询句法中直接查询派生实体:
ewtopic 和replies 是两个GridView 控件,
再来看看如何进行增删操作:
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 to sql:实体继承的使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!