| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 7531 人关注过本帖, 1 人收藏
标题:浅谈如何使用LINQ检索和操作数据库(续)
只看楼主 加入收藏
303770957
Rank: 11Rank: 11Rank: 11Rank: 11
等 级:小飞侠
威 望:6
帖 子:838
专家分:2125
注 册:2005-9-10
收藏(1)
 问题点数:0 回复次数:9 
浅谈如何使用LINQ检索和操作数据库(续)
1.LinqToObject(使用Linq查询对象)

using System;
using System.Collections.Generic;
using System.Linq;

namespace LINQtoObject
{
    class Program
    {
        public static int[] arry = {11,24,31,42,53,64,75,86,97,100,13,147,156,56,67,89,99 };
        
        static void Main(string[] args)
        {
            Shu2();//能被2整除的数
            Shu3();//能被3整除的数
            ShuYes2Yes3();//能被2整除也能被3整除的数
            ShuNot2Not3();//不能被2整除也不能被3整除的数
            Shu7((from a in arry select a).Where(a=>a%7==0));//能被7整除的数
            Console.ReadKey();//暂停观看结果
        }
        
        public static void Shu2()
        {
            Console.WriteLine("能被2整除的数有:");
            foreach (var ary in (from a in arry where a % 2 == 0 select a))
            {
                Console.Write("{0} ", ary);

            }
        }
      
        public static void Shu3()
        {
            Console.WriteLine("\n能被3整除的数有:");
            foreach (var ary in (from a in arry select a).Where(b => b % 3 == 0))
            {
                Console.Write("{0} ", ary);
            }
        }
      
        public static void ShuNot2Not3()
        {
            Console.WriteLine("\n不能被2整除也不能被3整除的数有:");
            foreach (var ary in (from a in arry where a % 2 != 0 select a).Where(b=>b%3!=0))
            {
                Console.Write("{0} ", ary);

            }
        }
        
        public static void ShuYes2Yes3()
        {
            Console.WriteLine("\n能被2整除也能被3整除的数有:");
            foreach (var ary in (from a in arry select a).Where(b => b % 3 == 0).Where(c=>c%2==0))
            {
                Console.Write("{0} ", ary);

            }
        }
      
        public static void Shu7(IEnumerable<int> Query)
        {
            Console.WriteLine("\n能被7整除的数有:");
            foreach (var ary in Query)
            {
                Console.Write("{0} ", ary);
            }
        }
    }
}

2.LinqToDataSet(使用Linq查询DataSet)

using System;
using System.Linq;//一定要记得添加引用
using System.Data;//用于Dataset
using System.Data.SqlClient;//用于
namespace LinqToDataSet
{
    class Program
    {
        static void Main(string[] args)
        {
            string conn = @"server=.;database=Northwind;uid=sa;pwd=Windows2008";
            string sqlstr = "select * from Customers";
            SqlDataAdapter da = new SqlDataAdapter(sqlstr,conn );
            DataSet ds = new DataSet();
            da.Fill(ds,"Customers");
            //****************************************************************
            IEnumerable<DataRow> dt = ds.Tables["Customers"].AsEnumerable();
            var query = from data in dt
                        where data.Field<string>("City")=="London"
                        orderby data["CompanyName"]
                        select new
                        {
                            CustomerID = data.Field<string>("CustomerID"),
                            CompanyName = data.Field<string>("CompanyName")
                         };
                    
            Console.WriteLine("Northwind数据库:");
            foreach(var a in query)
            {
                Console.WriteLine(\t" +a.CustomerID);
            }
            //****************************************************************
            Console.ReadKey();
        }
    }
}

3.LingToSQL(使用Linq查询SQL数据库)

using System;
using System.Linq;//一定要记得添加引用
using LinqNorthwind;//(可以用sqlmetal.exe工具直接生成,然后引入。)
namespace LinqToSQL
{
    class Program
    {
        public static string connString = @"server=.;database=Northwind;uid=sa;pwd=Windows2008";

        public static NorthwindDataContext db = new NorthwindDataContext(connString);
        
        static void Main(string[] args)
        {
            Console.WriteLine("Customers matching data:\n");

            DoLinqSelect(); //查询原始数据

            DoLinqInsert(); //插入新数据
            DoLinqSelect();

            DoLinqUpdate(); //修改新数据
            DoLinqSelect();

            DoLinqDelete(); //删除新数据
            DoLinqSelect();

            Console.ReadKey();//暂停观看结果
        }

        public static void DoLinqSelect() //查询
        {
            var customers = (from C in db.Customers select C).Where(c => c.City == "London");
            foreach (var cus in customers)
            {
                Console.WriteLine("CustomerID={0},City={1},CompanyName={2}",
                    cus.CustomerID, cus.City, );
            }

            Console.WriteLine("Totals: {0}", customers.Count());

        }

        public static void DoLinqInsert() //插入
        {
            Customers newCus = new Customers();
             = "AdventureWorks Cafe";
            newCus.CustomerID = "ADVCA";
            newCus.City = "London";
            db.Customers.InsertOnSubmit(newCus);
            db.SubmitChanges();//与数据库同步
            Console.WriteLine("\nCustomers matching 'ADVCA' already inserted.\n");
        }

        public static void DoLinqUpdate() //更新
        {
            Customers newCus = db.Customers.Single(a => a.CustomerID == "ADVCA");
             = "GloryKing";
            db.SubmitChanges();
            Console.WriteLine("\nCustomers matching 'ADVCA' already updated.\n");
        }

        public static void DoLinqDelete() //删除
        {
            Customers newCus = db.Customers.Single(c => c.CustomerID == "ADVCA");
            db.Customers.DeleteOnSubmit(newCus);
            db.SubmitChanges(); //与数据库同步
            Console.WriteLine("\nCustomers matching 'ADVCA' already deleted.\n");
        }

    }
}

---------------------------------------------------------------------------------------------------
运行结果:

Customers matching data:

CustomerID=AROUT,City=London,CompanyName=Around the Horn
CustomerID=BSBEV,City=London,CompanyName=B's Beverages
CustomerID=CONSH,City=London,CompanyName=Consolidated Holdings
CustomerID=EASTC,City=London,CompanyName=Eastern Connection
CustomerID=NORTS,City=London,CompanyName=North/South
CustomerID=SEVES,City=London,CompanyName=Seven Seas Imports
Totals: 6

Customers matching 'ADVCA' already inserted.

CustomerID=ADVCA,City=London,CompanyName=AdventureWorks Cafe
CustomerID=AROUT,City=London,CompanyName=Around the Horn
CustomerID=BSBEV,City=London,CompanyName=B's Beverages
CustomerID=CONSH,City=London,CompanyName=Consolidated Holdings
CustomerID=EASTC,City=London,CompanyName=Eastern Connection
CustomerID=NORTS,City=London,CompanyName=North/South
CustomerID=SEVES,City=London,CompanyName=Seven Seas Imports
Totals: 7

Customers matching 'ADVCA' already updated.

CustomerID=ADVCA,City=London,CompanyName=GloryKing
CustomerID=AROUT,City=London,CompanyName=Around the Horn
CustomerID=BSBEV,City=London,CompanyName=B's Beverages
CustomerID=CONSH,City=London,CompanyName=Consolidated Holdings
CustomerID=EASTC,City=London,CompanyName=Eastern Connection
CustomerID=NORTS,City=London,CompanyName=North/South
CustomerID=SEVES,City=London,CompanyName=Seven Seas Imports
Totals: 7

Customers matching 'ADVCA' already deleted.

CustomerID=AROUT,City=London,CompanyName=Around the Horn
CustomerID=BSBEV,City=London,CompanyName=B's Beverages
CustomerID=CONSH,City=London,CompanyName=Consolidated Holdings
CustomerID=EASTC,City=London,CompanyName=Eastern Connection
CustomerID=NORTS,City=London,CompanyName=North/South
CustomerID=SEVES,City=London,CompanyName=Seven Seas Imports
Totals: 6
---------------------------------------------------------------------------------------------------
SqlMetal.exe使用方法(只适用能添加到SQL数据库中的数据,Access数据库不适用):
1.可以Visual Studio 2008 命令提示符输入:sqlmetal /?  查看帮助信息
2.生成的文件位于 X:\Program Files\Microsoft Visual Studio 9.0\VC 目录下
3.SqlMetal.exe工具位于 X:\Program Files\Microsoft SDKs\Windows\v6.0A\bin 目录下
4.以下是用sqlmetal工具生成代码的实例:
(1)通过 SqlServer 创建cs代码:
  SqlMetal /conn:"server=.;database=Northwind;uid=sa;Password=Windows2008" /timeout:5 /views /functions /sprocs /namespace:LinqNorthwind /context:NorthwindDataContext /code:Northwind.cs

(2)通过 SqlServer 生成中间 dbml 文件:
  SqlMetal /conn:"server=.;database=Northwind;uid=sa;Password=Windows2008" /timeout:5 /views /functions /sprocs /namespace:LinqNorthwind /context:NorthwindDataContext /dbml:Northwind.dbml

(3)通过 dbml 生成包含外部映射的代码:
  SqlMetal /code:Northwind.cs /map:Northwind.map Northwind.dbml
  注意:用此命令时必须要保证 Northwind.dbml 在 X:\Program Files\Microsoft Visual Studio 9.0\VC 目录下

 (4)通过 SqlCE sdf 文件生成 dbml:
  SqlMetal /dbml:Northwind.dbml Northwind.sdf
  注意:用此命令时必须要保证 Northwind.sdf 在 X:\Program Files\Microsoft Visual Studio 9.0\VC 目录下
结语:亲爱的朋友们临近新年了,在这里我预祝你们新年快乐,在新的一年里有更多的收获,感谢你们的支持。
搜索更多相关主题的帖子: 检索 数据库 LINQ 
2010-02-08 14:13
bygg
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:乖乖的心中
等 级:版主
威 望:241
帖 子:13555
专家分:3076
注 册:2006-10-23
收藏
得分:0 
支持!

飘过~~
2010-02-08 17:32
cuinan128
Rank: 2
等 级:论坛游民
帖 子:20
专家分:55
注 册:2010-3-24
收藏
得分:0 
大家說的太好了  我頂一下

[url=http://www.]mbt sale[/url]
2010-03-27 08:56
duanzelong
该用户已被删除
收藏
得分:0 
提示: 作者被禁止或删除 内容自动屏蔽
2010-03-31 14:03
misswang
Rank: 8Rank: 8
来 自:湖北荆州
等 级:贵宾
威 望:15
帖 子:265
专家分:720
注 册:2010-3-11
收藏
得分:0 
顶起

misswp2010@
wangping103@
2010-04-02 09:24
lgwei
Rank: 1
等 级:新手上路
帖 子:2
专家分:0
注 册:2011-1-18
收藏
得分:0 
支持,好···
2011-01-19 09:04
wcp126
Rank: 1
等 级:等待验证会员
帖 子:95
专家分:7
注 册:2010-3-30
收藏
得分:0 
有没有用linq写的相关项目呀 ?跪求学习 79486743@
2012-02-13 10:37
CMYK
Rank: 2
等 级:论坛游民
帖 子:67
专家分:74
注 册:2011-9-19
收藏
得分:0 
2012-04-14 14:36
ninghz
Rank: 2
等 级:论坛游民
帖 子:34
专家分:34
注 册:2011-7-8
收藏
得分:0 

        如果Customers中的CustomerID没有“ADVCA”会报”序列中不包含任何元素“ 异常,建议先:            
bool flag = db.Customers.Any(a => a.CustomerID == "ADVCA");
            //Any返回的是bool类型 ,当返回真的时候再用Single 方法去找对象
            if (flag)
            {
                Customers newCus = db.Customers.Single(a => a.CustomerID == "ADVCA");
                = "GloryKing";
                db.SubmitChanges();
                Console.WriteLine("\nCustomers matching 'ADVCA' already updated.\n");
            }


程序改变生活
2012-05-15 17:24
qq8801103
Rank: 5Rank: 5
来 自:苏州中科大软件学院
等 级:职业侠客
威 望:1
帖 子:422
专家分:340
注 册:2009-10-8
收藏
得分:0 
支持

Discuz!  
好好学习  天天向上
2013-03-04 17:06
快速回复:浅谈如何使用LINQ检索和操作数据库(续)
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.038192 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved