C# Data Manipulation Series-13 SqlSugar Preliminary


0. Preface

Foreword, say goodbye to NHibernate for the time being (although I suddenly found this thing quite interesting, but not many people have seen it). I strode into SQLSugar, where many friends asked me to Amway. Well, I have always been called SugarSQL. It seems to be this, right?

This is an ORM framework developed by domestic developers. It is a lightweight framework (the latest version of sqlSugarCore is only about 290kb). The following figure is a functional description of sqlSugar:

image

From the figure, we can roughly see that the use of SqlSugar needs to create a SqlSugarClient object in advance. SqlSugar adds CRUD, entity information maintenance (mapping relationship), configuration (AOP/filter, etc.), modes (DbFirst, CodeFirst), and some tool classes on this basis. You can see that this is a simple and complete framework.

At the same time, SqlSugar has also further expanded the query. The following are the functions it supports and the enhancements in the query:

Okay, let's not talk nonsense, let's try how to use it first.

1. Installation

The environment in this section is dotnet + vscode. Because my Rider expired, I didn't bother to toss. The system is Linux again, so choose this method. As for the operation of Visual Studio and Rider, it is very simple, and it was introduced in the previous "C# Basic Series 16".

First build a solution, named DataProvider:

dotnet new sln --name DataProvider

Then create a SqlSugarDemo console project:

dotnet new console --name SqlSugarDemo

Add this project to the solution: (This step is to facilitate subsequent management)

dotnet sln add SqlSugarDemo

Then prepare to install  sqlSugarCore . SqlSugar has two versions, sqlSugarCore is used here, which is the version supported by .net core. The other is sqlSugar, which is based on .netframework 4.X. Our series is .net core, so we use sqlSugarCore.

Because we only SqlSugarDemoadd this package to the project , not to the entire solution, we need to switch the directory to SqlSugarDemo in advance:

cd SqlSugarDemo/

Then install sqlSugarCore using the command line:

dotnet add package sqlSugarCore

Or use NuGet:

Install-Package sqlSugarCore

After a while, you can see a successful installation message in the console:

log  : Restore completed in XX sec for XXXXXX/SqlSugarDemo/SqlSugarDemo.csproj.

2. Basic usage example

In the previous section, we successfully installed sqlSugarCore in the project, so in this section, we will lead our friends to explore SqlSugar together.

First create a normal model:

public class Person
{
   public int Id { get; set; }
   public string Name { get; set; }
   public int Age { get; set; }
}

Create an operation class and name it DefaultContext. According to the given document, SqlSugar needs to hold a SqlSugarClient object every time it manipulates data. Therefore, the definition of this class should be as follows:

public class DefaultContext
{
   public SqlSugarClient Client { get; }

   public DefaultContext(string connectionString, DbType dbType)
   {
       Client = new SqlSugarClient(new ConnectionConfig
       {
           ConnectionString = connectionString,//"Data Source=./demo.db",
           DbType = dbType,
           IsAutoCloseConnection = true,
       });
   }
}
  • ConnectionString: connection string

  • DbType: database type, a total of the following values

    • MySql

    • SqlServer

    • Sqlite

    • Oracle

    • PostgreSQL

  • IsAutoCloseConnection: Whether to automatically close the connection, it is recommended to be true, and the default is false. By default, it needs to be released manually

Then test the insert:

var context = new DefaultContext("Data Source=./demo.db", DbType.Sqlite);
context.Client.Insertable<Person>(new Person
{
   Age = 10,
   Name = "小明"
}).ExecuteCommand();

At this time, the following error is prompted: no such table: Person

image

The reason is simple, because there is no such table in the database demo.db. That is, SqlSugar does not automatically generate tables by default, but generates an empty shell database.

At this time, you need to add some configuration for the Client in the DefaultContext construction method:

Client.CodeFirst.InitTables<Person>();

The meaning of this line is to use CodeFirst mode to automatically generate the table Person.

Of course, this does not mean that we can continue. We also need to set the primary key strategy. When initializing the SqlSugarClient, modify it to:

Client = new SqlSugarClient(new ConnectionConfig
{
   ConnectionString = connectionString,//"Data Source=./demo.db",
   DbType = dbType,
   IsAutoCloseConnection = true,
   InitKeyType = InitKeyType.Attribute  //添加这行,意思是根据实体类去
发现主键
});

Then re-insert, the execution is successful.

Now for the query test:

var query = context.Client.Queryable<Person>();

query is an element of type ISugarQueryable<T>. This interface supports two query methods: method chain query and query expression:

var list = (from a in context.Client.Queryable<Person>()
           select a).ToList();
Console.WriteLine(list.Count);

In this way, a list of Person type is directly obtained.

Then, we will modify and delete these elements to test. First modify:

list[0].Age =22;
context.Client.Updateable(list[0]).ExecuteCommand();

Direct execution will prompt the following error:

image

This means that no primary key or search conditions are provided. According to its error message, we can know that there are two basic solutions:

Modification plan 1:

Add a primary key on the Person class and set self-growth.

public class Person
{
   [SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
   public int Id { get; set; }
   public string Name { get; set; }
   public int Age { get; set; }
}

Solution 2:

Add filter criteria:

context.Client.Updateable(list[0]).Where(t=>t.Name == "小明").ExecuteCommand();

I adopted the first method, added the primary key configuration, re-run, the execution result is correct.

Delete, after the update is completed, delete is also used normally:

context.Client.Deleteable(list[0]).ExecuteCommand();

3 summary

After a quick glance, I found that SqlSugar is also an ORM framework that makes me feel amazing, with comprehensive functions and very good efficiency. The next article will explore sqlSugar in depth for friends.




Guess you like

Origin blog.51cto.com/15060511/2639832