如何在网站开发中使用LINQ操作数据库

来源:互联网 发布:tita软件 编辑:程序博客网 时间:2024/06/08 10:53

开始之前先简单的介绍一下LINQ

    LINQ作为一种数据查询编码方式,本身并不是独立的开发语言,也不能进行应用程序的开发。但是在ASP.NET 4.0中,通过C#语言继承LINQ查询的代码,可以在任何源代码文件中使用。

    查询是一种从数据源检索数据的表达式,通常使用专门的查询语言来表示。随着变成技术的不断发展,人们已经为各种数据源开发了不同的语言,编程人员不得不对每种数据源或数据格式进行有针对性的学习。而LINQ的出现则改变了这种情况,它可以使用通用的基本编码模式来查询和转换不同的数据源,如XML文档、SQL数据库、ADO.NET数据集和.NET集合中的数据等。

     

下面先看一个简单的LINQ查询的例子:

创建一个ASP.NET Web应用程序,在“Default.aspx.cs”文件中编写如下代码:

    protected void Page_Load(object sender, EventArgs e)    {        string[] wordArry = { "Lilei", "hANmeiMei", "zhAngSan", "LISi", "WangwU"};        int i = 0;        var upperLowerWords =            from w in wordArry            select new { Upper = w.ToUpper(), Lower = w.ToLower() };        foreach (var word in upperLowerWords)        {            Response.Write(wordArry[i] + "单词的大写为:" + word.Upper + "<BR>");            Response.Write(wordArry[i] + "单词的小写为:" + word.Lower + "<BR>");            i++;        }}

运行结果如下:



查询表达式必须以from 为关键字的子句开头,并且必须以select或者group关键字的子句结尾。在第一个from子句和最后一个select 或者group子句之间,查询表达式可以包含一个或多个由下列关键字组成的可选子句:where、orderby、join、select等关键字。同时还可以使用Into关键字让join或group子句的结果能够作为同一查询表达式中附加查询子句的数据源。

(orderby关键字:Ascending关键字表示默认方式按照递增顺序排列。Descending表示关键字逆序排列。)

看几个例子了解一下:

        IEnumberable<User> userQuery =            from age in User            orderby user.age            select age;

        var userQueryByName =            from u in User            group u by u.age;        foreach (var userGroup in userQuery)        {            Console.WriteLine(userQuery.name);            foreach (User user in userGroup)            {                Console.WriteLine("{0}", user.age);            }        }


        int[] arry1 = {1, 3, 5, 7, 9 };        int[] arry2 = {2, 4, 6, 8, 10, 11 };        var query = from val1 in arry1                    join var2 in arry2 on val1 + 1 equals var2                    select new { VAL1 = val1, VAL2 = var2 };


        int[] arry = { 0, 1, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };        var lint = arry.Select(iNum => iNum < 10 ? iNum : 0);        foreach (var temp1 in lint)        {            Response.Write(temp1.ToString());        }



下面来看一下如何在网站开发中使用LINQ操作数据库

    首先,在数据库中建立数据库 test(本人使用sqlserver2008),在其中建立表userinfo,如下:



    然后开始操作vs2010

1、创建ASP.NET Web应用程序。命名“LinqTest”

2、点击 “视图” --> “服务器资源管理器”。右键单击“数据连接”,选择“添加连接”


3、在“添加连接”对话框中按照提示信息填写,并测试连接,使配置成功。


4、在“服务器资源管理器”窗口中的数据连接节点下就可以看到刚才添加好的数据库了。


5、右键项网站名称,选择“添加新项”菜单。弹出框中选择“已安装模板”,列表中选择“LINQ to SQL类”,输入需要的名称,单机添加。


6、此时在网站根目录下就会看到相应的文件


7、双击 “TestLinqDataClasses.dbml”,然后从“服务器资源管理器”中将表拖进主窗口(”对象关系设计器“界面)。


9、打开文件“TestLinqDataClasses.designer.cs”,就可以看到已经自动生成了SQL实体类以及强类型 TestLinqDataClassesDataContext的定义

[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="test")]public partial class TestLinqDataClassesDataContext : System.Data.Linq.DataContext{private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();  #region 可扩展性方法定义  partial void OnCreated();  #endregionpublic TestLinqDataClassesDataContext() : base(global::System.Configuration.ConfigurationManager.ConnectionStrings["testConnectionString"].ConnectionString, mappingSource){OnCreated();}public TestLinqDataClassesDataContext(string connection) : base(connection, mappingSource){OnCreated();}public TestLinqDataClassesDataContext(System.Data.IDbConnection connection) : base(connection, mappingSource){OnCreated();}public TestLinqDataClassesDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource){OnCreated();}public TestLinqDataClassesDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) : base(connection, mappingSource){OnCreated();}public System.Data.Linq.Table<userinfo> userinfo{get{return this.GetTable<userinfo>();}}}[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.userinfo")]public partial class userinfo{private string _id;private string _name;private string _age;private string _sex;private string _job;public userinfo(){}[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_id", DbType="NChar(10)")]public string id{get{return this._id;}set{if ((this._id != value)){this._id = value;}}}[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_name", DbType="NChar(10)")]public string name{get{return this._name;}set{if ((this._name != value)){this._name = value;}}}[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_age", DbType="NChar(10)")]public string age{get{return this._age;}set{if ((this._age != value)){this._age = value;}}}[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_sex", DbType="NChar(10)")]public string sex{get{return this._sex;}set{if ((this._sex != value)){this._sex = value;}}}[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_job", DbType="NVarChar(50)")]public string job{get{return this._job;}set{if ((this._job != value)){this._job = value;}}}}

10、现在就可以在网站中使用LINQ查询数据库了。

在“Default.aspx.cs”文件的“Page_Load”事件中添加查询代码,就可以了。如下:

    protected void Page_Load(object sender, EventArgs e)    {        TestLinqDataClassesDataContext testUser = new TestLinqDataClassesDataContext();        var userQuery = from u in testUser.userinfo                        select u;        foreach (var value in userQuery)        {            Response.Write("姓名:" + value.name + " 性别:" + value.sex +  " 年龄" + value.age + "<BR>");        }    }

运行结果如下:


和我们数据库中的结果一致。


至此,我们以及完成了LINQ在项目中的使用。


参考文章:

《ASP.NET4.0从入门到精通》 张正礼 王坚宁编著 清华大学出版社2011年7月第1版


0 0
原创粉丝点击