(LINQ 学习系列)(6)Linq教程实例: 使用自写类代码来访问数据

1.    自定义一个和数据表相对应的类.例如建议StudentClass.cs
    /**
    *  meetweb@sohu.com 
     *  Modify By 2012-3
     * 
*/
    using System;
   using System.Collections.Generic;
    using System.Linq;
    using System.Data.Linq.Mapping;
    using System.Data;
    using System.Reflection;
    using System.Linq.Expressions;
    using System.ComponentModel;
   
    namespace LinqTest
    {
        [Table(Name = "student")]
        class StudentClass
        {
            private int _ID;
  
           private string _StudentName;
   
            private System.Nullable<int> _Old;
   
            private string _Sex;
            [Column(Name = "ID")]
            public int ID
            {
                set
                {
                    _ID  = value;
                }
                get
                {
                    return _ID ;
                }
            }
               [Column(Name = "StudentName")]
            public string StudentName
            {
               get
                {
                    return this._StudentName;
               }
                set
                {
                        this._StudentName = value;
                }
            }
             [Column(Name = "Old")]
            public System.Nullable<int> Old
            {
                get
                {
                    return this._Old;
                }
                set
                {
                   if (this._Old != value)
                   {
                    
                       this._Old = value;
                  
                    }
                }
            }
             [Column(Name = "Sex")]
           public string Sex
            {
                get
                {
                   return this._Sex;
               }                set               {
                   if ((this._Sex != value))
                   {
                 
                        this._Sex = value;
                 
                    }
               }
           }
          
        }
   }
  

1.    建一个窗体 Frmindividuation
   private void Frmindividuation_Load(object sender, EventArgs e)
        {
            GetData();
        }
        //Get The Data Table
        private void GetData()
        {
            IDbConnection conn = new SqlConnection(sqlconStr);
            conn.Open();
            DataContext ctx = new DataContext(conn);
            Table<StudentClass> dx = ctx.GetTable<StudentClass>();
            this.dataGridView1.DataSource = dx.ToList();

}

2.      运行结果如下图

由上面结果可以看出,自己建类和使用DataContent建立的方式基本实现的效果一致. 某些人提出自己写类特别麻烦,其实有很多工具可以生产大家所需要的基本类

原文地址:https://www.cnblogs.com/meetweb/p/2432124.html