NHibernate学习初识NHibernate

要学NHibernate之前先了解一下什么是ORM

ORM(对象关系映射 Object Relational Mapping)是一种解决面向对象与关系型数据库之间的不匹配的技术,如图

AIB6I`T[$1]9QHQ9HZUGAR7       %V0Q6EN4MY`9$ELZ7L@YQ[5

现在把Student表中的记录全部查询出来显示在DataGrid表格中,步骤如下:

1.查询Student表的全部记录,并填充到DataTable表中

    public class DBHelp
    {
        public static DataTable GetStudent(SqlConnection con)
        {
            string sqlcmd = "select id,name from Student";
            
            SqlCommand cmd = new SqlCommand(sqlcmd, con);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);

            DataTable table = new DataTable();
            adapter.Fill(table);
            return table;
        }
    }

2.创建一个Student对象的集合List<Student> 来保存DataTable中的数据

    public class QueryControl
    {
        public static List<Student> QueryStudent()
        {
            SqlConnection con = App.GetCon();
            DataTable table= DBHelp.GetStudent(con);
            Student stu = null;
            List<Student> lst = new List<Student>();
            //循环赋值
            foreach (DataRow row in table.Rows)
            {
                stu = new Student();
                stu.Id =(int)row["Id"];
                stu.Name = row["Name"].ToString();
                lst.Add(stu);
            }
            return lst;
        }
    }

3.(WPF)将这个对象绑定到DataGrid的ItemsSource

        XAML:

        <my:DataGrid AutoGenerateColumns="False" Margin="12,12,12,93" Name="dataGrid1" >
            <my:DataGrid.Columns>
                <my:DataGridTextColumn Header="Id"  Width="100" Binding="{Binding Path=Id}"/>
                <my:DataGridTextColumn Header="Name" Width="150" Binding="{Binding Path=Name}"/>
            </my:DataGrid.Columns>
        </my:DataGrid>
   按钮代码:  List<Student> lst = QueryControl.QueryStudent();
             dataGrid1.ItemsSource = lst;

结果:

Run

在这个过程中,程序员会把大量的时间浪费在第二步上面,就是如何把数据库表的数据转化为面向对象的数据表示方法,像上面的代码那样,如果数据库有什么改动,那么结果就可想而知了,会牵扯到很多的代码改动,如果数据库表很多的话,那就更惨了.ORM的出来就是来解决这个问题的,他很好的封装了在面向对象与关系型数据库进行交互时的数据交换的过程,使程序员能够更方便的进行数据交换的操作(说白了就是人家已经针对这一块写了通用的Dll,我们直接拿过来用就可以实现数据库与实体类之间的数据交换).对这一块我也很无奈,以前自己也写了一个通用的类,做法是把实体类用反射的方法获取一个实体类成员的数组,然后再用SQL把相关的表的字段查询出来,然后用循环依次赋值,同时拼成sql语句,最后执行,不过最终没用在项目里应用.

下一篇写一个简单的实例!!

原文地址:https://www.cnblogs.com/wangshuai/p/1784767.html