C#中的LINQ toSQL

  • LINQ to SQL 基于ADO.NET 将数据表和行映射成类对象。
  • LINQ to SQL从.net 自定义属性或xml文档中获取映射信息。这些信息用于自动将对象持久保存至关系型数据库中。
  • 数据表可以map成一个类,数据表中的列将被map类中的属性,表与表之间的关系将以额外的属性表示。
  • LINQ to sql 能够自动跟踪对象的修改。并通过动态生成的SQL语句进行更新数据库。

数据库如下:

在这里插入图片描述

  1. 创建实体类
[Table(Name="Products")]
     public class Products
        {
            public int ProductID;
            public string ProductName ;  
        }

LINQ to SQL 的Table属性位于System.data.Linq.Mapping命名空间中。在进行开发的过程中需要添加命名空间
在这里插入图片描述

在这里插入图片描述

  1. 关联
    为了将实体类与数据表关联起来,需要提供实体类型中各属性与数据表中各列的对应关系,这个可以通过Column属性给出,如下:
[Table(Name="Products")]
        public class Products
        {
            [Column(IsPrimaryKey = true)]
            public int ProductID{get;set;}

            [Column(Name="ProductName")]

            public string ProductName { get; set; }
        }
  1. dataContext
    提供 LINQ (语言集成查询) 访问和更改跟踪、 列表和Microsoft SharePoint Foundation网站的文档库。

  2. 具体工程代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
using System.Xml;
using System.Data.Linq.Mapping;
using System.Data.Linq;

 
namespace ConsoleApplication1
{
    class Program
    {
       
        [Table(Name="Products")]
        public class Products
        {
            [Column(IsPrimaryKey = true)]
            public int ProductID{get;set;}

            [Column(Name="ProductName")]

            public string ProductName { get; set; }
        }
       
        static void Main()
        {
           SqlConnection conn = new SqlConnection(@"Data Source=;Initial Catalog=Store;User ID=sa;Password= 123;");
           DataContext ctx = new DataContext(conn);

           var stores = from store in ctx.GetTable<Products>()
                        where store.ProductID >= 2
                        select store;

           foreach (var store in stores)
           {
               Console.WriteLine(store.ProductName);           
           }
           Console.ReadLine();
        }
    }  
}
  1. 执行结果如下:
    在这里插入图片描述

总结:

  1. 打开数据库
  2. 生成SQL查询语句
  3. 执行SQL查询语句
  4. 将执行结果填充至对象中