惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

K
Kaspersky official blog
T
Threat Research - Cisco Blogs
N
News and Events Feed by Topic
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - 叶小钗
Security Latest
Security Latest
Spread Privacy
Spread Privacy
aimingoo的专栏
aimingoo的专栏
N
News and Events Feed by Topic
Webroot Blog
Webroot Blog
U
Unit 42
Cyberwarzone
Cyberwarzone
小众软件
小众软件
Scott Helme
Scott Helme
Engineering at Meta
Engineering at Meta
Microsoft Security Blog
Microsoft Security Blog
T
The Blog of Author Tim Ferriss
A
About on SuperTechFans
爱范儿
爱范儿
S
Schneier on Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Schneier on Security
Schneier on Security
Latest news
Latest news
GbyAI
GbyAI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Simon Willison's Weblog
Simon Willison's Weblog
The Register - Security
The Register - Security
WordPress大学
WordPress大学
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
PCI Perspectives
PCI Perspectives
Jina AI
Jina AI
AI
AI
NISL@THU
NISL@THU
I
Intezer
G
GRAHAM CLULEY
B
Blog
S
Secure Thoughts
IT之家
IT之家
宝玉的分享
宝玉的分享
Recent Announcements
Recent Announcements
Y
Y Combinator Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
酷 壳 – CoolShell
酷 壳 – CoolShell
有赞技术团队
有赞技术团队
V2EX - 技术
V2EX - 技术
Recorded Future
Recorded Future
Hacker News - Newest:
Hacker News - Newest: "LLM"

博客园 - Animax!

The Tao of Programming Light weight Framework (AnyBase) -- 通信模块说明 关于WinIO.DLL的键盘输入模拟 Light weight Framework (AnyBase) -- Core 模块说明 开源项目 Light weight Framework (AnyBase) 发布 DB4o的缓存机制 Winfrom界面异步操作的一个解决方法 db4o 研究--性能测试 Asp.net动态数据(Dynamic Data) 笔记一 MVC — 笔记 WF笔记 – Workflow概念 WCF Demo – Http、TCP Host - Animax! LINQ TO SQL 笔记 — 存储过程、并发与事务 WCF笔记 - 绑定 WCF 笔记 正则表达式[转载整理] - Animax! - 博客园 LINQ 笔记 - 语法与关键字 LINQ 笔记- Lambda Excel导入SQL - Animax! - 博客园
LINQ 笔记 - LINQ to SQL 基本数据操作 - Animax!
Animax! · 2008-03-13 · via 博客园 - Animax!

首先需要讲一下 DataContext 类 。
这个类是 LINQ to SQL 框架的主入口点。DataContext 是通过数据库连接映射的所有实体的源。

要在数据库操作上玩 SQL 除了 DataContext 还需要一个数据表的实体类。

在VS 2008 里面,可以直接使用生成 "LINQ to SQL 类" 来解决懒人的动手问题。

添加 "LINQ to SQL 类" 后,可以直接使用 "服务资源管理器" 添加所需要的数据表到 "LINQ to SQL 类",
这样就能直接生成 DataContext 的派生类和表的实体类。

下面这个例子,使用 Northwind 数据库。

    // NorthwindDataContext 是 DataContext 派生类, 用于连接数据库与实体
    NorthwindDataContext n = new NorthwindDataContext(
@"Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
    
    
// 操作 Orders 数据表
    var s = from n1 in n.Orders
            
where n1.OrderID % 10 == 0
            select 
new
            
{
                ID 
= n1.OrderID,
                Name 
= n1.ShipName
            }
;

    
foreach (var s1 in s)
    
{
        Console.Write(s1.ID);
        Console.Write(
" | ");
        Console.Write(s1.Name);
        Console.WriteLine();
    }

    

    Console.ReadKey();
    
/*
10300 | Magazzini Alimentari Riuniti
10400 | Eastern Connection
10500 | La maison d'Asie
10600 | Hungry Coyote Import Store
10700 | Save-a-lot Markets
10800 | Seven Seas Imports
10900 | Wellington Importadora
11000 | Rattlesnake Canyon Grocery
*/

插入数据:

若要执行 SQL Insert,只需向您已创建的对象模型添加对象,然后对 DataContext 调用 SubmitChanges 即可。

    NorthwindDataContext n = new NorthwindDataContext(
@"Data Source=.;Initial Catalog=Northwind;Integrated Security=True");

    
// 建立对Region表的LINQ查询
    var Regions = from n1 in n.Region
                  select n1;

    
// 向Region插入数据
    Region r = new Region();
    r.RegionID 
= 999;
    r.RegionDescription 
= "test";
    n.Region.InsertOnSubmit(r); 
// 添加记录到
    n.SubmitChanges();  // 通知数据库更改记录

    
// 开始查询,延迟执行
    foreach (var Region in Regions)
    
{
        Console.Write(Region.RegionID);
        Console.Write(
" | ");
        Console.Write(Region.RegionDescription);
        Console.WriteLine();
    }
            

    Console.ReadKey();

/*
1 | Eastern
2 | Western
3 | Northern
4 | Southern
999 | test
*/

  这里创建一个新示例数据库 DBTest.mdf
  数据库只有一个 Table 表

  CREATE TABLE [Table]
    (
    ID 
int NOT NULL IDENTITY (11PRIMARY KEY,
    Value 
varchar(50NULL
    )


    

    并为这个数据表添加一个"LINQ to SQL 类",该文件命名为:TestDB.dbml

更新数据:

  // 把数据库中ID等于10记录的值修改为"null"
  static void Main()
  
{

      TestDBDataContext TestDB 
= new TestDBDataContext(@"路径"DBTest.mdf");

      var L 
= from v in TestDB.Table
              
where v.ID == 10
              select v;

      
foreach (var I in L)
      
{
          I.Value 
= "null"//修改值
      }

      TestDB.SubmitChanges(); 
// 向数据库提交刷新

      
      
foreach (var I in L)  // 显示修改后的值
      {
          Console.WriteLine(I.Value);
      }

      
      Console.ReadKey();
  }

删除记录:


  
// 把数据库中value为"null"的记录删除
  static void Main()
  
{

      TestDBDataContext TestDB 
= new TestDBDataContext(@"路径"DBTest.mdf");

      var L 
= from v in TestDB.Table
              
where v.Value == "null"
              select v;


      
foreach (var I in L)
      
{
          TestDB.Table.DeleteOnSubmit(I); 
// 删除记录
      }

      TestDB.SubmitChanges(); 
// 向数据库提交刷新


      Console.ReadKey();
  }

存储过程:

  存储过程:

    ALTER PROCEDURE insertToTable
      
@value varchar(50)
    
AS
      
insert into [Table] (value) values (@value)
      
RETURN


 

  在"服务器资源管理器"中打开这个存储过程,然后拖到刚才的"LINQ to SQL 类" -- TestDB.dbml 中,
在TestDB.designer.cs文件里面,IDE自动在 class TestDBDataContext(DataContext的派生类)
里面为这个insertToTable存储过程添加了如下方法代码:

        [Function(Name="dbo.insertToTable")]
        
public int insertToTable([Parameter(DbType="VarChar(50)")] string value)
        
{
            IExecuteResult result 
= this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), value);
            
return ((int)(result.ReturnValue));
        }


        

然后只需要在客户端使用一下这个方法,就完成了存储过程的调用:

    static void Main()
    
{

        TestDBDataContext TestDB 
= new TestDBDataContext(@"路径"DBTest.mdf");

        TestDB.insertToTable(
"AppTest");  // 使用InsertToTable存储过程为"Table"表添加一行记录

    }