Linq查询累继承与DataContext

有省市区的数据表如图:

现在需要查询Type=3的所有名称

首先需要建立一个和现有表结构相同的实体对象

namespace Mode
{
    //表明可以自定义
    [Table(Name = "Area")]
    public class Area
    {
        //列字段,注意,字段类型必须和数据库一致
        [Column]
        public int id
        {
            get;
            set;
        }
        [Column]
        public string Areaname
        {
            get;
            set;
        }
        [Column]
        public string Areanum
        {
            get;
            set;
        }
        [Column]
        public int Type
        {
            get;
            set;
        }
        [Column]
        public string ParentID
        {
            get;
            set;
        }
    }
}

接下来调用查询方法,进行数据库信息查询

  /// <summary>
        /// linq 查询数据表
        /// </summary>
        private static void LinqToSql()
        {
            using (DataContext conn = new DataContext(@"server=HAPPY-PC;User ID=sa;Password=happy;database=XinShiDai4.13;Connection Reset=FALSE;Max Pool Size = 512;"))
            {
                //初始化实例表
                Table<Area> Area = conn.GetTable<Area>();
                //查询
                var items = from c in Area where c.Type == 3 select c;
                //遍历查询
                foreach (var item in items)
                {
                    Console.WriteLine(item.Areaname);
                }
            }
            Console.ReadKey();

        }

运行结果为东城区
西城区
崇文区
宣武区
朝阳区
丰台区
石景山区
海淀区………………

 

//************************查询数据包进行前台绑定显示**********************************

     private void LinqToDataSource()
        {
            //记录时间
            Stopwatch watch = new Stopwatch();
            watch.Start();
            //打开链接
            using (DataContext conn = new DataContext(@"server=HAPPY-PC;User ID=sa;Password=happy;database=XinShiDai4.13;Connection Reset=FALSE;Max Pool Size = 512;"))
            {
                //添加日志
                //StreamWriter sw = new StreamWriter("d:\\dialy.txt", true);
                //conn.Log = sw;
                //知道数据对象
                IEnumerable<Area> table = conn.ExecuteQuery<Area>("select * from area");
                this.GridView1.DataSource = table;
                this.GridView1.DataBind();

                //不知道数据对象的时候使用var
                //var table = conn.ExecuteQuery<Area>("select * from area");
                //this.GridView1.DataSource = table;
                //this.GridView1.DataBind();
                //sw.Close();
             
            }
            watch.Stop();
            Response.Write(watch.Elapsed.Milliseconds.ToString());
        }

显示结果为:

 

 

 

 

 

 

posted on 2012-04-16 14:30  高兴happy  阅读(1572)  评论(0编辑  收藏  举报