LINQ to SQL的CRUD操作

时间:2023-03-08 15:51:22
  • 创建数据对象模型
sqlmetal /code:"C:\MyProjects\VS2008\Data\LinqConsoleApp2\LinqConsoleApp2\northwnd.cs" /language.csharp "C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Data\northwnd.mdf" /pluralize

创建数据对象

  • 使用数据对象模型(CRUD)
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;

 namespace LinqConsoleApp2
 {
     class Program
     {
         static void Main(string[] args)
         {
             //指定数据源
             Northwnd db = new Northwnd(@"C:\Program Files\Microsoft SQL Server\MSSQL.2\MSSQL\Data\northwnd.mdf");
             //查询
             IQueryable<Customer> custQuery =
                 from cust in db.Customers
                 where cust.City == "London"
                 select cust;
             Console.WriteLine("查询后的操作结果:");
             foreach (Customer cust in custQuery)
             {
                 Console.WriteLine("\t{0},{1}", cust.CustomerID, cust.CompanyName);
             }
             //插入
             Customer newCust = new Customer();
             newCust.CompanyName = "中国电信";
             newCust.CustomerID = "CTTC";
             db.Customers.InsertOnSubmit(newCust);
             db.SubmitChanges();
             Console.WriteLine("插入后的操作结果:");
             foreach(var c in db.Customers.Where(cust => cust.CustomerID.Contains("TC"))){
                 Console.WriteLine("\t{0},{1}",c.CustomerID,c.CompanyName);
             }
             //更新
             var exitCust = (from c in db.Customers
                             where c.CustomerID == "CTTC"
                             select c).First();
             exitCust.CompanyName = "中国联通";
             db.SubmitChanges();
             Console.WriteLine("更新后的操作结果:");
             foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("TC")))
             {
                 Console.WriteLine("\t{0},{1}", c.CustomerID, c.CompanyName);
             }
             //删除
             var exitCust2 = (from c in db.Customers
                              where c.CustomerID == "CTTC"
                              select c).First();
             db.Customers.DeleteOnSubmit(exitCust2);
             db.SubmitChanges();
             Console.WriteLine("删除后的操作结果:");
             foreach (var c in db.Customers.Where(cust => cust.CustomerID.Contains("TC")))
             {
                 Console.WriteLine("\t{0},{1}", c.CustomerID, c.CompanyName);
             }

             Console.ReadLine();
         }//static void Main(string[] args)
     }//class Program
 }

使用数据对象

  • 运行结果展示

LINQ to SQL的CRUD操作

  • 备注

需引用System.Data.Linq导入相应的命名空间