zoukankan      html  css  js  c++  java
  • 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) { }

    }

           然后,我们来测试一下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表中加一些数据,如下图:

           启动程序得到如下测试结果:


           当然,你也可以在查询句法中直接查询派生实体:

           newtopicreplies是两个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();

  • 相关阅读:
    HDU5320 : Fan Li
    BZOJ3069 : [Pa2011]Hard Choice 艰难的选择
    BZOJ4227 : 城市
    BZOJ4216 : Pig
    BZOJ1171 : 大sz的游戏
    BZOJ4182 : Shopping
    BZOJ3482 : [COCI2013]hiperprostor
    BZOJ3919 : [Baltic2014]portals
    BZOJ3711 : [PA2014]Druzyny
    BZOJ1580 : [Usaco2009 Hol]Cattle Bruisers 杀手游戏
  • 原文地址:https://www.cnblogs.com/kevin2013/p/1749043.html
Copyright © 2011-2022 走看看