LINQ查询Sql Server 数据库

 

简单查询

1.首先 ,新建一个LinqToSql类文件.把需要查询的表,拖入类文件的设计界面.接下来就可以使用它了.

2.页面拖一个GridView


      

表信息:LINQ查询Sql Server 数据库_第1张图片

3.后台代码

//实例化Linq链接对象
           DataClasses1DataContext datacontent = new DataClasses1DataContext(ConfigurationManager.AppSettings["SQLString"].ToString());
           //查询表达式
           var data = from info in datacontent.Message
                      select new
                      {

 

                           资讯标题 = info.Mess_Title,
                          资讯内容 = info.Mess_Content

                           };

   //绑定数据
  GridView1.DataSource = data;
  GridView1.DataBind();

多项查询:

LINQ查询Sql Server 数据库_第2张图片

表结构:LINQ查询Sql Server 数据库_第3张图片

查询类别是下拉框内容, 关键字是文本框中内容的 信息

查询按钮事件下代码:

DataClasses1DataContext datacontent;
string str = ConfigurationManager.AppSettings["SQLString"].ToString();
     

if (TextBox1.Text == "")
           {
               int value = int.Parse(DropDownList1.SelectedValue);
               //实例化Linq链接对象
               datacontent = new DataClasses1DataContext();  //实例化Linq链接对象

               //查询表达式
               var data = from info in datacontent.Message
                          where info.Mess_ModuleID == value     //Mess_ModuleID 为资讯类别id
                          select new
                          {

                              资讯标题 = info.Mess_Title,
                              资讯内容 = info.Mess_Content


                          };

               //绑定数据
               GridView1.DataSource = data;
               GridView1.DataBind();

           }
           else
           {
               int value = int.Parse(DropDownList1.SelectedValue);

               datacontent = new DataClasses1DataContext();
               //查询表达式
               var data = from info in datacontent.Message
                          where info.Mess_Content.Contains(TextBox1.Text.Trim()) && info.Mess_ModuleID == int.Parse(DropDownList1.SelectedValue)  //Mess_Contents是资讯内容
                          select new
                          {

                              资讯标题 = info.Mess_Title,
                              资讯内容 = info.Mess_Content


                          };

               //绑定数据
               GridView1.DataSource = data;
               GridView1.DataBind();


           }

转载于:https://www.cnblogs.com/Mr-Joe/archive/2012/01/30/2332300.html

你可能感兴趣的:(LINQ查询Sql Server 数据库)