初次接触linq

Linq很早就出来了 一直没有心思去学习一下   现在开始接触学习Ling!!!希望通过看文档 查资料深入一下!!!

模仿linq风格写一段:

        int[] i = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
        var temp = from num in i where num % 2 == 0 select num;
        foreach (var item in temp)
        {
            Response.Write(item + "<br/>");
        }

最基本使用LINQ TO SQL

新建一个LINQ TO SQL文件 例如取名product 生成文件Product.dbml   往Product.dbml.layout中拖入数据表 自动生成数据库连接代码

后台绑定GridView代码:

ProductDataContext pa = new ProductDataContext();

GridView1.DataSource = from pandc in pa.PandC where pandc.PID > 20 select new{ pandc.PID,pandc.PNAME };
   GridView1.DataBind();

ProductDataContext 为自动生成的类 只需要实例化就可以使用

pa.PandC 指pa类中的数据表PandC 还有其他表的话同理 例如pa.PRODUCT_ALL

where后加条件

发现Linq中要查询多个列的话要使用select new{ pandc.PID,pandc.PNAME }这样的写法

感觉from pandc in pa.PandC 中的pandc in pa.PandC 其实就相当于pa.PandC 之前的pandc 不过是方便后来的查询条件和查询项 故pandc 其实是什么都可以 这不重要

另外个人觉得的重点是:

生成的Product.dbml文件中的Product.designer.cs文件 由于数据表是拖进去的 它生成的数据库连接字符串是自动生成的 难免有时候会不合我们的需要 所以有需要的话可以更改:

 

自动生成的Product.designer.cs文件中的连接数据库为:

base(global::System.Configuration.ConfigurationManager.ConnectionStrings["IORIZFConnectionString"].ConnectionString, mappingSource)

它对应的web.config文件的代码为:

<add name="IORIZFConnectionString" connectionString="Data Source=IORI;Initial Catalog=IORIZF;Integrated Security=True"
   providerName="System.Data.SqlClient" /> 这也是自动生成的

按自己的需要 我更改了一下:

Product.designer.cs文件中更改为:

base(global::System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(), mappingSource)

将web.config文件的代码注释掉并添加:

<appSettings>
    <add key="ConnectionString" value="server=.; database=IORIZF; uid=sa; pwd=475238"/>
</appSettings>

posted @ 2012-04-20 23:46  sidihu  阅读(169)  评论(0编辑  收藏  举报