ORM之linq2db

前言:今天来学习下ORM框架中的linq2db,本文将从linq2db的介绍、linq2db的优点、linq2db的简单使用做个学习记录

linq2db的介绍

        LINQ to DB是最快的LINQ数据库访问库,在POCO对象和数据库之间提供简单,轻便,快速且类型安全的层。

linq2db的优点

  • 简单、轻便、快捷、能快速实现CRUD
  • 集成了linq语法和lambada表达式的写法
  • 使用T4模板自动生成实体类,不用使用其他代码生成器了。方便
  • 类型安全

linq2db的使用

项目依赖项中使用NuGet程序包添加:linq2db.SqlServer

可以看到有很多linq2db.XXX的,可能不同数据库需要引入的不同,我们这里用SQLServer,后续用到其他数据库的时候再补充

引入之后,项目中会多一个文件夹 如下:

 我们从文件夹下面找到第一个文件CopyMe.SqlServer.tt.txt 看看文件夹里面的内容如下:

<#@ template language="C#" debug="True" hostSpecific="True" #>
<#@ output extension=".generated.cs"                        #>

<#@ include file="$(LinqToDBT4SqlServerTemplatesPath)LinqToDB.SqlServer.Tools.ttinclude" once="true" #>
<#@ include file="$(LinqToDBT4SqlServerTemplatesPath)PluralizationService.ttinclude"     once="true" #>
<#
    /*
        1. Create new *.tt file (e.g. MyDatabase.tt) in a folder where you would like to generate your data model
           and copy content from this file to it.  在要生成数据模型的文件夹中创建新的*.tt文件(例如MyDatabase.tt)并将此文件中的内容复制到其中
            

For example:

            MyProject
                DataModels
                    MyDatabase.tt
 
        2. Modify the connection settings below to connect to your database. 修改下面的连接设置以连接到数据库。

        3. Add connection string to the web/app.config file: 将连接字符串添加到web/app.config文件:


            <connectionStrings>
                <add name="MyDatabase" providerName="System.Data.SqlClient"
                    connectionString="Data Source=.;Database=MyDatabase;User Id=User;Password=TestPassword;" />
            </connectionStrings>

        4. To access your database use the following code:

            using (var db = new MyDatabaseDB())
            {
                var q =
                    from c in db.Customers
                    select c;

                foreach (var c in q)
                    Console.WriteLine(c.ContactName);
            }

        5. See more at https://linq2db.github.io/articles/T4.html

        If you need to use the Microsoft.SqlServer.Types namespace, install the Microsoft.SqlServer.Types nuget,
        and replace the following include at the top of this file:

            "$(ProjectDir)LinqToDB.TemplatesLinqToDB.SqlServer.Tools.ttinclude"

        with

            "$(ProjectDir)LinqToDB.TemplatesLinqToDB.SqlServer.SqlTypes.Tools.ttinclude"

        IMPORTANT: if running .tt file gives you error like this:
        "error : Failed to resolve include text for file: C:...$(LinqToDBT4<DB>TemplatesPath)LinqToDB.<DB>.Tools.ttinclude"
        check tt file properties.
        Custom tool must be set to TextTemplatingFileGenerator, not TextTemplatingFilePreprocessor or any other value.
    */

    NamespaceName = "DataModels";

    // to configure GetSchemaOptions properties, add them here, before load metadata call

    LoadSqlServerMetadata("MyServer", "MyDatabase", "User", "Password");
//    LoadSqlServerMetadata(".", "MyDatabase"); // Integrated Security
//    LoadSqlServerMetadata(string connectionString);

    // to adjust loaded database model before generation, add your code here, after load metadata, but before GenerateModel() call

    GenerateModel();
#>

步骤如下:

  1.    在要生成数据模型的文件夹中创建新的*.tt文件(例如MyDatabase.tt)并将此文件中的内容复制到其中
  2. 修改下面的连接设置以连接到数据库
  3. 将连接字符串添加到web/app.config文件
  4.    是具体使用方法
  5.    更多用法参考网址:https://linq2db.github.io/articles/T4.html

参照步骤 创建了一个文件夹来存放生成的实体类 如下:

 将文件后缀改为*.tt时会提示:

 点击确定,生成的实体类文件如下:

然后点开文件就是连接的数据库的实体类文件 ,Amazing!!!

然后CopyMe.SqlServer.tt.txt 备注的第三点是用法 ,来看下使用方法

linq2db的RRUD:

  • C-Create 创建/新增:
            using (var db = new PandaPTPAPDB())
            {
                //1:新增
                db.Insert(new Task());
                //2:批量新增
                db.Insert(new List<Task>());
            }
  • R-Retrieve 检索/查询:
 using (var db = new PandaPTPAPDB())
            {
                //1:查询所有
                var list = (from c in db.Tasks select c).ToList();

                //2:分页查询:
                int pageIndex = 1, pageSize = 10;

                var pageList = (from c in db.Tasks select c).Skip((pageIndex - 1) * pageSize + 1).Take(pageSize).ToList();

                //3:查询单条
                var model = (from c in db.Tasks select c).FirstOrDefault(x=>x.Id.ToString()=="12345");

            }

可以看到访问数据库都是通过linq语句来进行的,linq语句的用就很多了,后续完善

  • U-Update 更新:
            using (var db = new PandaPTPAPDB())
            {
                //1:更新
                db.Update(new Task());
                //2:批量更新
                db.Update(new List<Task>());
            }
  • D-Delete 删除:
            using (var db = new PandaPTPAPDB())
            {
                //1:删除
                db.Delete(new Task());
                //2:批量删除
                db.Delete(new List<Task>());
            }

以上就是linq2db的最最最最基本的用法,总的来说,使用起来挺便捷的,不用自己创建实体类,访问都是基于linq表达式,还是相当方便的。

不积跬步,无以至千里;不积小流,无以成江海。ヾ(◍°∇°◍)ノ゙
原文地址:https://www.cnblogs.com/jiangxianshen/p/15356720.html