• Stars
    star
    1,047
  • Rank 42,306 (Top 0.9 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created about 7 years ago
  • Updated 3 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

SmartSql = MyBatis in C# + .NET Core+ Cache(Memory | Redis) + R/W Splitting + PropertyChangedTrack +Dynamic Repository + InvokeSync + Diagnostics

SmartSql (Document)

Overview

SmartSql = MyBatis + Cache(Memory | Redis) + R/W Splitting +Dynamic Repository + Diagnostics ......


Simple, efficient, high-performance, scalable, monitoring, progressive development!

How does she work?

SmartSql draws on MyBatis's ideas, uses XML to manage SQL, and provides several filter tags to eliminate various if/else judgment branches at the code level. SmartSql will manage your SQL and filter the tags to maintain your various conditional judgments at the code level to make your code more beautiful.

Why Choose SmartSql?

The Orm,linq of the DotNet system, which is mostly Linq, is very good, eliminating the developer's reliance on SQL. But it ignores the fact that SQL itself is not complex, and that it is difficult for developers to write Linq to generate good performance SQL in complex query scenarios, and I believe that students who have used EF must have this experience: "I think about how SQL writes, and then I write Linq, It's over. You may also want to see what SQL output of Linq is like. " It was a very bad experience. To be absolutely optimized for SQL, developers must have absolute control over SQL. In addition, SQL itself is very simple, why add a layer of translators?

SmartSql has been out of formal open source for more than two years, in the production environment after several micro-service verification. There are also some businesses that are using SmartSql (if you are also using SmartSql Welcome to submit issue)Who is using SmartSql. Has now joined NCC。 The future (Roadmap-2019) SmartSql will continue to add new features to help developers improve efficiency. Welcome to submit Issue https://github.com/dotnetcore/SmartSql/issues.

So why not Dapper, or DbHelper?

Dapper is really good and good performance, but the code that will be ceded to you is filled with SQL and various judgment branches that will make code maintenance difficult to read and maintain. In addition, Dapper only provides DataReader to Entity anti-serialization function. And SmartSql offers a number of features to improve developer efficiency.

Feature Overview

SmartSql

Dynamic Repository

Dynamic Agent Repository (SmartSql.DyRepository) components are SmartSql very unique features that simplify the use of SmartSql. There is little intrusion into the business code. It can be said that using ISqlMapper is the original method, and DyRepository automatically helps you implement these methods.

DyRepository only need to define the Repository interface, through a simple configuration can automatically implement these interfaces and register in the IoC container, when used injection instant acquisition implementation. The principle is to obtain the Scope and SqlId in the XML file of SmartSql through the naming rules of the interface and interface method, use the parameters of the interface method as the Request, and automatically judge the query or perform the operation through the SQL in the XML, and finally realize the ISqlMapper Call.

0. Define Repository interfaces

    public interface IUserRepository : IRepository<User, long>
    {
    }

1. Injection dependencies

            services.AddSmartSql()
                .AddRepositoryFromAssembly(options => { options.AssemblyString = "SmartSql.Starter.Repository"; });

2. Use

    public class UserService
    {
        IUserRepository userRepository;

        public UserService(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }
    }

SmartSql Best practices -> SmartCode

SmartCode

By SmartCode Developers simply configure the database connection to build everything that is required for the solution, including, but not limited to:

  • Solution Engineering
  • Give you a restore.
  ReStore:
    Type: Process
    Parameters: 
      FileName: powershell
      WorkingDirectory: '{{Project.Output.Path}}'
      Args: dotnet restore
  • Docker
    • Building Docker Mirroring & Running Instances
 BuildDocker:
    Type: Process
    Parameters:
      FileName: powershell
      WorkingDirectory: '{{Project.Output.Path}}'
      Args: docker build -t {{Project.Parameters.DockerImage}}:v1.0.0 .

  RunDocker:
    Type: Process
    Parameters:
      FileName: powershell
      WorkingDirectory: '{{Project.Output.Path}}'
      Args: docker run --name {{Project.Parameters.DockerImage}} --rm -d -p 8008:80 {{Project.Parameters.DockerImage}}:v1.0.0 .
  • Open a browser by the way
  RunChrome:
    Type: Process
    Parameters:
      FileName: C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
      CreateNoWindow: false
      Args: http://localhost:8008/swagger

Docker

SmartCode SmartCode SmartCode SmartCode

Directory structure generated by SmartCode

SmartCode-directory-structure

Read and write separation

SmartSql Read and write separation is especially easy, just provide a good configuration can be:

  <Database>
    <DbProvider Name="PostgreSql"/>
    <Write Name="WriteDB" ConnectionString="${Master}"/>
    <Read Name="ReadDb-1" ConnectionString="${Slave-0}" Weight="100"/>
    <Read Name="ReadDb-2" ConnectionString="${Slave-1}" Weight="100"/>
  </Database>

Cache

  • Lru Least recently used algorithms
  • Fifo Advanced first-out algorithm
  • RedisCacheProvider
  • Other inherited self-ICacheProvider cache types are available
<Caches>
    <Cache Id="LruCache" Type="Lru">
      <Property Name="CacheSize" Value="10"/>
      <FlushOnExecute Statement="AllPrimitive.Insert"/>
      <FlushInterval Hours="1" Minutes="0" Seconds="0"/>
    </Cache>
    <Cache Id="FifoCache" Type="Fifo">
      <Property Name="CacheSize" Value="10"/>
    </Cache>
    <Cache Id="RedisCache" Type="${RedisCacheProvider}">
      <Property Name="ConnectionString" Value="${Redis}" />
      <FlushInterval Seconds="60"/>
    </Cache>
  </Caches>
   <Statement Id="QueryByLruCache"  Cache="LruCache">
      SELECT Top 6 T.* From T_User T;
    </Statement>

Type Handler

The SmartSql is implemented internally DotNet the main types of type handlers, and some types of compatible type conversion processors are provided, as well as more commonly used JsonTypeHanlder.

    <TypeHandler PropertyType="SmartSql.Test.Entities.UserInfo,SmartSql.Test" Type="${JsonTypeHandler`}">
      <Properties>
        <Property Name="DateFormat" Value="yyyy-MM-dd mm:ss"/>
        <Property Name="NamingStrategy" Value="Camel"/>
      </Properties>
    </TypeHandler>

CUD Code generation

SmartSql also provides CUD extension functions to help developers generate good CUD-SQL for direct developer use without having to write any configuration.

public static TEntity GetById<TEntity, TPrimaryKey>(this ISqlMapper);
public static TPrimaryKey Insert<TEntity, TPrimaryKey>(this ISqlMapper sqlMapper, TEntity entity);
public static int DyUpdate<TEntity>(this ISqlMapper sqlMapper, object entity);
public static int Update<TEntity>(this ISqlMapper sqlMapper, TEntity entity);
public static int DeleteById<TEntity, TPrimaryKey>(this ISqlMapper sqlMapper, TPrimaryKey id);
public static int DeleteMany<TEntity, TPrimaryKey>(this ISqlMapper sqlMapper, IEnumerable<TPrimaryKey> ids);

Id Generator

SnowflakeId

<IdGenerators>
    <IdGenerator Name="SnowflakeId" Type="SnowflakeId">
      <Properties>
        <Property Name="WorkerIdBits" Value="10"/>
        <Property Name="WorkerId" Value="888"/>
        <Property Name="Sequence" Value="1"/>
      </Properties>
    </IdGenerator>
</IdGenerators>
    <Statement Id="Insert">
      <IdGenerator Name="SnowflakeId" Id="Id"/>
      INSERT INTO T_UseIdGenEntity
      (
      Id,
      Name
      )
      VALUES
      (
      @Id,
      @Name
      );
      Select @Id;
    </Statement>
var id = SqlMapper.ExecuteScalar<long>(new RequestContext
            {
                Scope = nameof(UseIdGenEntity),
                SqlId = "Insert",
                Request = new UseIdGenEntity()
                {
                    Name = "SmartSql"
                }
            });

DbSequence

<IdGenerators>
    <IdGenerator Name="DbSequence" Type="DbSequence">
      <Properties>
        <Property Name="Step" Value="10"/>
        <Property Name="SequenceSql" Value="Select Next Value For IdSequence;"/>
      </Properties>
    </IdGenerator>
</IdGenerators>
    <Statement Id="InsertByDbSequence">
      <IdGenerator Name="DbSequence" Id="Id"/>
      INSERT INTO T_UseIdGenEntity
      (
      Id,
      Name
      )
      VALUES
      (
      @Id,
      @Name
      );
      Select @Id;
    </Statement>
            var id = SqlMapper.ExecuteScalar<long>(new RequestContext
            {
                Scope = nameof(UseIdGenEntity),
                SqlId = "InsertByDbSequence",
                Request = new UseIdGenEntity()
                {
                    Name = "SmartSql"
                }
            });

AOP Transaction

        [Transaction]
        public virtual long AddWithTran(User user)
        {
            return _userRepository.Insert(user);
        }

Transaction nesting

When a transaction is nested, the transaction attribute annotation of the child function is no longer turned on, and the transaction that calls the function by the parent is used instead

        [Transaction]
        public virtual long AddWithTranWrap(User user)
        {
            return AddWithTran(user);
        }

BulkInsert

using (var dbSession= SqlMapper.SessionStore.Open())
            {
                var data = SqlMapper.GetDataTable(new RequestContext
                {
                    Scope = nameof(AllPrimitive),
                    SqlId = "Query",
                    Request = new { Taken = 100 }
                });
                data.TableName = "T_AllPrimitive";
                IBulkInsert bulkInsert = new BulkInsert(dbSession);
                bulkInsert.Table = data;
                bulkInsert.Insert();
            }

Skywalking Monitoring

SmartSql currently supports Skywalking monitoring and is enabled by installing the SkyAPM-dotnet agent. The following is a partial screenshot.

Monitoring execution commands

Query

View whether the cache is cached and the number of records returned

Query-Detail

View executed SQL statements

Query-Statement

Transaction

Transaction

Error

Error

Exception stack Trace

Error-Detail

Nuget Packages

Package NuGet Stable Downloads
SmartSql SmartSql SmartSql
SmartSql.Schema SmartSql.Schema SmartSql.Schema
SmartSql.TypeHandler SmartSql.TypeHandler SmartSql.TypeHandler
SmartSql.DyRepository SmartSql.DyRepository SmartSql.DyRepository
SmartSql.DIExtension SmartSql.DIExtension SmartSql.DIExtension
SmartSql.Cache.Redis SmartSql.Cache.Redis SmartSql.Cache.Redis
SmartSql.ScriptTag SmartSql.ScriptTag SmartSql.ScriptTag
SmartSql.AOP SmartSql.AOP SmartSql.AOP
SmartSql.Options SmartSql.Options SmartSql.Options
SmartSql.Bulk SmartSql.Bulk SmartSql.Bulk
SmartSql.Bulk.SqlServer SmartSql.Bulk.SqlServer SmartSql.Bulk.SqlServer
SmartSql.Bulk.MsSqlServer SmartSql.Bulk.MsSqlServer SmartSql.Bulk.MsSqlServer
SmartSql.Bulk.PostgreSql SmartSql.Bulk.PostgreSql SmartSql.Bulk.PostgreSql
SmartSql.Bulk.MySql SmartSql.Bulk.MySql SmartSql.Bulk.MySql
SmartSql.Bulk.MySqlConnector SmartSql.Bulk.MySqlConnector SmartSql.Bulk.MySqlConnector
SmartSql.InvokeSync SmartSql.InvokeSync SmartSql.InvokeSync
SmartSql.InvokeSync.Kafka SmartSql.InvokeSync.Kafka SmartSql.InvokeSync.Kafka
SmartSql.InvokeSync.RabbitMQ SmartSql.InvokeSync.RabbitMQ SmartSql.InvokeSync.RabbitMQ

Demo

SmartSql.Sample.AspNetCore

QQGroup

Click on the link to join the QQ group [SmartSql official QQ group]:604762592

More Repositories

1

FastGithub

github加速神器,解决github打不开、用户头像无法加载、releases无法上传下载、git-clone、git-pull、git-push失败等问题
C#
13,273
star
2

CAP

Distributed transaction solution in micro-service base on eventually consistency, also an eventbus with Outbox pattern
C#
6,267
star
3

Util

Util是一个.Net平台下的应用框架,旨在提升中小团队的开发能力,由工具类、分层架构基类、Ui组件,配套代码生成模板,权限等组成。
C#
4,306
star
4

WTM

Use WTM to write .netcore app fast !!!
C#
4,111
star
5

FreeSql

🦄 .NET aot orm, C# orm, VB.NET orm, Mysql orm, Postgresql orm, SqlServer orm, Oracle orm, Sqlite orm, Firebird orm, 达梦 orm, 人大金仓 orm, 神通 orm, 翰高 orm, 南大通用 orm, 虚谷 orm, 国产 orm, Clickhouse orm, QuestDB orm, MsAccess orm.
C#
3,935
star
6

DotnetSpider

DotnetSpider, a .NET standard web crawling library. It is lightweight, efficient and fast high-level web crawling & scraping framework
C#
3,753
star
7

osharp

OSharp是一个基于.Net6.0的快速开发框架,框架对 AspNetCore 的配置、依赖注入、日志、缓存、实体框架、Mvc(WebApi)、身份认证、功能权限、数据权限等模块进行更高一级的自动化封装,并规范了一套业务实现的代码结构与操作流程,使 .Net 框架更易于应用到实际项目开发中。
C#
2,663
star
8

Magicodes.IE

Import and export general library, support Dto import and export, template export, fancy export and dynamic export, support Excel, Csv, Word, Pdf and Html.
C#
2,035
star
9

WebApiClient

An open source project based on the HttpClient. You only need to define the c# interface and modify the related features to invoke the client library of the remote http interface asynchronously.
C#
1,990
star
10

NPOI

A .NET library for reading and writing Microsoft Office binary and OOXML file formats.
C#
1,877
star
11

EasyCaching

💥 EasyCaching is an open source caching library that contains basic usages and some advanced usages of caching which can help us to handle caching more easier!
C#
1,736
star
12

BootstrapBlazor

A set of enterprise-class UI components based on Bootstrap and Blazor
JavaScript
1,733
star
13

AspectCore-Framework

AspectCore is an AOP-based cross platform framework for .NET Standard.
C#
1,641
star
14

AgileConfig

基于.NET Core开发的轻量级分布式配置中心 / .NET Core lightweight configuration server
C#
1,400
star
15

Natasha

基于 Roslyn 的 C# 动态程序集构建库,该库允许开发者在运行时使用 C# 代码构建域 / 程序集 / 类 / 结构体 / 枚举 / 接口 / 方法等,使得程序在运行的时候可以增加新的模块及功能。Natasha 集成了域管理/插件管理,可以实现域隔离,域卸载,热拔插等功能。 该库遵循完整的编译流程,提供完整的错误提示, 可自动添加引用,完善的数据结构构建模板让开发者只专注于程序集脚本的编写,兼容 stanadard2.0 / netcoreapp3.0+, 跨平台,统一、简便的链式 API。 且我们会尽快修复您的问题及回复您的 issue.
C#
1,370
star
16

HttpReports

HttpReports is an APM (application performance monitor) system for .Net Core.
C#
1,261
star
17

sharding-core

high performance lightweight solution for efcore sharding table and sharding database support read-write-separation .一款ef-core下高性能、轻量级针对分表分库读写分离的解决方案,具有零依赖、零学习成本、零业务代码入侵
C#
1,073
star
18

FlubuCore

A cross platform build and deployment automation system for building projects and executing deployment scripts using C# code.
C#
894
star
19

Alipay.AopSdk.Core

支付宝(Alipay)服务端SDK,采用.NET Standard 2.0,支持.NET Core >=2.0,与官方SDK接口完全相同。完全可以按照官方文档进行开发。除了支持支付以外,官方SDK支持的功能本SDK全部支持,比如生活号、服务窗、行业合作等,且用法几乎一样,代码都可参考官方文档代码。
C#
782
star
20

SmartCode

SmartCode = IDataSource -> IBuildTask -> IOutput => Build Everything!!!
C#
567
star
21

CanalSharp

Alibaba mysql database binlog subscription & consumer components Canal's .NET client.
C#
559
star
22

aspnetcore-doc-cn

The Simplified Chinese edition of Microsoft ASP.NET Core documentation, translated by .NET Core Community and .NET China Community.
C#
522
star
23

Home

Home repo of .NET Core Community
299
star
24

mocha

Mocha is an application performance monitor tools based on OpenTelemetry, which also provides a scalable platform for observability data analysis and storage.
C#
132
star
25

Collections

Utilities and extensions for Collections includes Collections.Paginable and so on...
C#
88
star
26

EntityFrameworkCore.KingbaseES

Entity Framework Core provider for KingbaseES Database
C#
33
star
27

FlubuCore.Examples

Examples for FlubuCore - a cross platform build automation tool for building projects and executing deployment scripts using C# code.
C#
31
star
28

wind-rises

26
star
29

EntityFrameworkCore.GaussDB

Entity Framework Core provider for GaussDB Database
C#
21
star
30

Compile.Environment

When using the Roslyn library for dynamic compilation, you can introduce the library to provide a dynamic compilation environment.
10
star
31

SourceLink.Environment

Provide an inheritable NuGet package for the SourceLink feature.
7
star
32

projects

This repository is the site of NCC Projects include both Top-Level projects and Sandbox projects.
CSS
5
star
33

Natasha.Docs

The document for Natasha
JavaScript
4
star
34

dotnetcore.github.io

.NET Core Community Official WebSite
HTML
2
star
35

DotNetCore.GaussDB

It's the foundation of DotNetCore.EntityFrameworkCore.GaussDB
C#
2
star