首页 > 数据库 >无涯教程-LINQ - SQL查询

无涯教程-LINQ - SQL查询

时间:2023-12-10 11:31:55浏览次数:41  
标签:Name db 无涯 LINQ ContactNo employee SQL Employee

LINQ to SQL提供了用于将关系数据作为对象进行管理的基础结构(运行时)。它是.NET Framework 3.5版的组件,可以将对象模型的语言集成查询转换为SQL,然后将这些查询发送到数据库以供执行。从数据库获取输出后,LINQ to SQL再次将其转换为对象。

LINQ to SQL简介

对于大多数ASP.NET开发人员而言,LINQ to SQL(也称为DLINQ)是Language Integrated Query的激动人心的部分,因为它允许使用常规的LINQ表达式查询SQL Server数据库中的数据。它还允许更新,删除和插入数据,但是它遭受的唯一缺点是它对SQL Server数据库的限制。但是,通过ADO.NET,LINQ to SQL有很多好处,如降低了复杂性,减少了几行编码等等。

下图显示了LINQ to SQL的执行体系结构。

LINQ SQL Architecture

LINQ to SQL使用

步骤1  -  与数据库服务器进行新的“Data Connection”。

LINQ to SQL

步骤2  -  将LINQ添加到SQL类文件

LINQ to SQL

步骤3  -  从数据库中选择表,并将其拖放到新的LINQ to SQL类文件中。

LINQ to SQL

步骤4  -  将表添加到类文件中。

LINQ to SQL

LINQ to SQL查询

使用LINQ to SQL执行查询的规则与标准LINQ查询的规则相似,即查询是延迟执行还是立即执行。在使用LINQ to SQL执行查询时,有许多组件在起作用,以下是这些组件。

  • LINQ to SQL API          - 代表应用程序请求查询执行,并将其发送到LINQ to SQL Provider。

  • LINQ to SQL Provider - 将查询转换为Transact SQL(T-SQL),并将新查询发送到ADO Provider进行执行。

  • ADO Provider - 执行查询后,将输出以DataReader的形式发送到LINQ to SQL Provider,然后将其转换为用户对象形式。

应该注意的是,在执行LINQ to SQL查询之前,通过DataContext类连接到数据源至关重要。

添加或插入数据

C#

using System;
using System.Linq;

namespace LINQtoSQL {
   class LinqToSQLCRUD {
      static void Main(string[] args) {
      
         string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString();

         LinqToSQLDataContext db = new LinqToSQLDataContext(connectString);           

         //Create new Employee
		 
         Employee newEmployee = new Employee();
         newEmployee.Name = "Michael";
         newEmployee.Email = "[email protected]";
         newEmployee.ContactNo = "343434343";
         newEmployee.DepartmentId = 3;
         newEmployee.Address = "Michael - USA";

         //Add new Employee to database
         db.Employees.InsertOnSubmit(newEmployee);

         //Save changes to Database.
         db.SubmitChanges();

         //Get new Inserted Employee            
         Employee insertedEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals("Michael"));

         Console.WriteLine("Employee Id={0} , Name={1}, Email={2}, ContactNo={3}, Address={4}",
                          insertedEmployee.EmployeeId, insertedEmployee.Name, insertedEmployee.Email, 
                          insertedEmployee.ContactNo, insertedEmployee.Address);

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

Module Module1

   Sub Main()
   
      Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString()

      Dim db As New LinqToSQLDataContext(connectString)

      Dim newEmployee As New Employee()
	  
      newEmployee.Name = "Michael"
      newEmployee.Email = "[email protected]"
      newEmployee.ContactNo = "343434343"
      newEmployee.DepartmentId = 3
      newEmployee.Address = "Michael - USA"
     
      db.Employees.InsertOnSubmit(newEmployee)
     
      db.SubmitChanges()
     
      Dim insertedEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("Michael"))

      Console.WriteLine("Employee Id={0} , Name={1}, Email={2}, ContactNo={3}, 
         Address={4}", insertedEmployee.EmployeeId, insertedEmployee.Name,
         insertedEmployee.Email, insertedEmployee.ContactNo, insertedEmployee.Address)

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	 
   End Sub
  
End Module

上面的C#或VB代码编译并运行时,将产生以下输出-

Emplyee ID=4, Name=Michael, [email protected], ContactNo=
343434343, Address=Michael - USA

Press any key to continue.

更新数据

C#

using System;
using System.Linq;

namespace LINQtoSQL {
   class LinqToSQLCRUD {
      static void Main(string[] args) {
      
         string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString();

         LinqToSQLDataContext db = new LinqToSQLDataContext(connectString);

         //Get Employee for update
         Employee employee = db.Employees.FirstOrDefault(e =>e.Name.Equals("Michael"));

         employee.Name = "George Michael";
         employee.Email = "[email protected]";
         employee.ContactNo = "99999999";
         employee.DepartmentId = 2;
         employee.Address = "Michael George - UK";

         //Save changes to Database.
         db.SubmitChanges();
         
         Employee updatedEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals("George Michael"));

         Console.WriteLine("Employee Id={0} , Name={1}, Email={2}, ContactNo={3}, Address={4}",
                          updatedEmployee.EmployeeId, updatedEmployee.Name, updatedEmployee.Email, 
                          updatedEmployee.ContactNo, updatedEmployee.Address);

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

Module Module1

   Sub Main()
  
      Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString()

      Dim db As New LinqToSQLDataContext(connectString)

      Dim employee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("Michael"))

      employee.Name = "George Michael"
      employee.Email = "[email protected]"
      employee.ContactNo = "99999999"
      employee.DepartmentId = 2
      employee.Address = "Michael George - UK"

      db.SubmitChanges()
          
      Dim updatedEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("George Michael"))

      Console.WriteLine("Employee Id={0} , Name={1}, Email={2}, ContactNo={3},
         Address={4}", updatedEmployee.EmployeeId, updatedEmployee.Name, 
         updatedEmployee.Email, updatedEmployee.ContactNo, updatedEmployee.Address)

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
	  
   End Sub
   
End Module

上面的C#或Vb代码编译并运行时,将产生以下输出-

Emplyee ID=4, Name=George Michael, [email protected], ContactNo=
999999999, Address=Michael George - UK

Press any key to continue.

删除数据

C#

using System;
using System.Linq;

namespace LINQtoSQL {
   class LinqToSQLCRUD {
      static void Main(string[] args) {
      
         string connectString = System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToString();

         LinqToSQLDataContext db = newLinqToSQLDataContext(connectString);


         Employee deleteEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals("George Michael"));

         //删除 Employee
         db.Employees.DeleteOnSubmit(deleteEmployee);

         //Save changes to Database.
         db.SubmitChanges();

         //Get All Employee from Database
         var employeeList = db.Employees;
         foreach (Employee employee in employeeList) {
            Console.WriteLine("Employee Id={0} , Name={1}, Email={2}, ContactNo={3}",
               employee.EmployeeId, employee.Name, employee.Email, employee.ContactNo);
         }            

         Console.WriteLine("\nPress any key to continue.");
         Console.ReadKey();
      }
   }
}

VB

Module Module1

   Sub Main()
   
      Dim connectString As String = System.Configuration.ConfigurationManager.ConnectionStrings("LinqToSQLDBConnectionString").ToString()

      Dim db As New LinqToSQLDataContext(connectString)

      Dim deleteEmployee As Employee = db.Employees.FirstOrDefault(Function(e) e.Name.Equals("George Michael"))

      db.Employees.DeleteOnSubmit(deleteEmployee)

      db.SubmitChanges()

      Dim employeeList = db.Employees
	  
      For Each employee As Employee In employeeList
         Console.WriteLine("Employee Id={0} , Name={1}, Email={2}, ContactNo={3}",
            employee.EmployeeId, employee.Name, employee.Email, employee.ContactNo)
      Next 

      Console.WriteLine(vbLf & "Press any key to continue.")
      Console.ReadKey()
   End Sub
   
End Module

上面的C#或VB代码编译并运行时,将产生以下输出-

Emplyee ID=1, Name=William, [email protected], ContactNo=999999999
Emplyee ID=2, Name=Miley, [email protected], ContactNo=999999999
Emplyee ID=3, Name=Benjamin, [email protected], ContactNo=

Press any key to continue.

参考链接

https://www.learnfk.com/linq/linq-sql.html

标签:Name,db,无涯,LINQ,ContactNo,employee,SQL,Employee
From: https://blog.51cto.com/u_14033984/8759198

相关文章

  • python3使用pandas备份mysql数据表
    操作系统:CentOS7.6_x64Python版本:3.9.12MySQL版本:5.7.38日常开发过程中,会遇到mysql数据表的备份需求,需要针对单独的数据表进行备份并定时清理数据。今天记录下python3如何使用pandas进行mysql数据表的备份,我将从以下几个方面进行展开: 数据表备份逻辑描述 使用的相关......
  • MySQL 数据库操作指南:LIMIT,OFFSET 和 JOIN 的使用
    限制结果您可以通过使用"LIMIT"语句来限制查询返回的记录数量。以下是一个示例,获取您自己的Python服务器中"customers"表中的前5条记录:importmysql.connectormydb=mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",......
  • 无涯教程-LINQ - 环境设置
    在开始LINQ程序之前,最好首先了解设置LINQ环境的细微差别,LINQ需要一个.NET框架,这是一个革命性的平台,可以具有多种应用程序,LINQ查询可以方便地用C#或VisualBasic编写。Microsoft通过VisualStudio提供了针对这两种语言的工具,即C#和VisualBasic。无涯教程的示例都是在VisualSt......
  • MySQL 数据库操作指南:LIMIT,OFFSET 和 JOIN 的使用
    限制结果您可以通过使用"LIMIT"语句来限制查询返回的记录数量。以下是一个示例,获取您自己的Python服务器中"customers"表中的前5条记录:importmysql.connectormydb=mysql.connector.connect(host="localhost",user="yourusername",password="yourpassword",......
  • mysql set column sha2(uuid(),512) as column default value via trigger
    mysql>showcreatetablet3;+-------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------......
  • Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communicatio
    1、错误原因项目测试Swagger的时候,接口请求一直在那转,出不来数据,其他的配置都正常呀,我就很纳闷,今天记录一下。com.mysql.cj.jdbc.exceptions.CommunicationsException:CommunicationslinkfailureThelastpacketsentsuccessfullytotheserverwas0millisecondsago.The......
  • sql中的substring()、to_char()、extract()、concat()等函数
    ERROR:functionpg_catalog.substring(timestampwithouttimezone,integer,integer)doesnotexistLINE1:SELECTu.username,l.description,l.ip,SUBSTRING(l.createdate,…^HINT:Nofunctionmatchesthegivennameandargumenttypes.Youmightneedtoadde......
  • pg库实现sql行转列
    ......
  • sql中sysdate 和 current_date 的区别及to_char( tv_date, ‘YYYY-MM-DD‘)当天时间与
    sysdate和current_date的区别在oracle中current_date与sysdate都是显示当前系统时间,其结果基本相同,但是有三点区别:1.current_date返回的是当前会话时间,而sysdate返回的是服务器时间;2.current_date有时比sysdate快一秒,这可能是四舍五入的结果;3.如果修改......
  • 导出MySQL数据字典
    使用SQL语句的形式在可视化工具(如使用Navicat)中执行以下语句,然后将查询结果导出为表格USEinformation_schema;SELECTT.TABLE_SCHEMAAS'数据库名称',T.TABLE_NAMEAS'表名',T.TABLE_TYPEAS'表类型',T.ENGINEAS'数据库引擎',C.ORDINAL_POSITIONAS'字段编号',......