SqlSugar released, an easy-to-use open source ORM framework

Introduction

Sqlsugar has been perfectly compatible with .NET5 for the first time and has been used by some people. Many people are worried that problems encountered with the open source framework cannot be solved, leading to abandonment of previous work. You can rest assured that using SqlSugar, except for detailed documentation and a large number of years User accumulation,

SqlSugar also provides a complete service, so that your project has no worries

 

Advantages: simple and easy to use, complete functions, high performance, lightweight, complete services

Support database: MySql, SqlServer, Sqlite, Oracle, postgresql, Dameng, Renda Jincang

 

Free service

1. Basic usage consultation

2. BUG submission

3. Adopt suggestions and needs

4. The open source code can be used for any commercial project to download without charge

5. QQ exchange group discussion 995692596 (free) 654015377 (1800/2000 crowded) 726648662 ((full) 225982985 (full)

 

Practice Tip 1: Performance Monitoring

Through this function, we can easily monitor the sql that executes more than 1 second, and can get his C# code file and line number and method

  SqlSugarClient db = new SqlSugarClient( new ConnectionConfig() 
   { 
                DbType = DbType.SqlServer, 
                ConnectionString = Config.ConnectionString, 
                InitKeyType = InitKeyType.Attribute, 
                IsAutoCloseConnection = true 
               
   }); 
    db.Aop.OnLogExecuted = (sql, p) => 
    { 
         / / Execution time exceeds 1 second 
        if (db.Ado.SqlExecutionTime.TotalSeconds> 1 ) 
        { 
            // Code CS file name 
            var fileName=db.Ado.SqlStackTrace.FirstFileName;
             // Number of lines of code 
            var fileLine = db.Ado.SqlStackTrace.FirstLine;
             // Method name 
            var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
             // db.Ado.SqlStackTrace.MyStackTraceList[1 ].xxx Get the information of the upper method 
         } 
   };

 

Practice function 2: Data change monitoring

When our code deletes the specific code, adds the specific code, which column is modified, you will not be able to retrieve it without the powerful logging function. SqlSugar can easily achieve high-security data logging.

db.Aop.OnDiffLogEvent = it => 
{ 
                var editBeforeData = it.BeforeData; //The record before the operation contains: Field description, column name, value, table name, table description 
                var editAfterData = it.AfterData; //The record after the operation contains: Field description, column name Value table name table description 
                var sql = it.Sql;
                 var parameter = it.Parameters;
                 var data = it.BusinessData; // The object you passed in will be displayed here 
                var time = it.Time;
                 var   diffType=it.DiffType; // enum insert, update and delete   
                  
                // Write logic 
}; 
  
//Add 
db.Insertable( newStudent() {Name = " beforeName " }) 
.EnableDiffLogEvent( new {title = " I am inserting " }) //Enable the log and add business objects 
. 
ExecuteReturnIdentity (); 
  
//Modify db.Updateable <Student>( new Student () 
            { 
                Id = id, 
                CreateTime = DateTime.Now, 
                Name = " afterName " , 
                SchoolId = 2 
            }) 
.EnableDiffLogEvent( 
//Delete ) //Start log
.ExecuteCommand();
  
db.Deleteable <Student> (id) 
.EnableDiffLogEvent( )//Start log.ExecuteCommand 
();

 

Practice function 3: JSON type perfect support

SqlSugar not only supports PgSql's Json array type, even if your database does not have a JSON type, you can use JSON objects for storage

ublic class UnitJsonTest
{
   [SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
   public int Id { get; set; }
    [SqlSugar.SugarColumn(ColumnDataType ="varchar(max)", IsJson = true)]
   public Order Order { get; set; }
   public string Name{get;set;}
}
Db.Insertable(new UnitJsonTest() { Name="json1",Order = new Order { Id = 1, Name = "order1" } }).ExecuteCommand();
var list = Db.Queryable<UnitJsonTest>().ToList();

 

Practice function 4: sub-database + sub-table + multi-database transaction

1. Create a database dynamically

The following code will create db1 and db2 databases

string conn = "server=.;uid=sa;pwd=haosql;database={0}";
var db = new SqlSugarClient(new ConnectionConfig()
{
DbType = SqlSugar.DbType.SqlServer,
ConnectionString = string.Format(conn, "db1"),
InitKeyType=InitKeyType.Attribute
});
db.DbMaintenance.CreateDatabase();
var db2 = new SqlSugarClient(new ConnectionConfig()
{
DbType = SqlSugar.DbType.SqlServer,
ConnectionString = string.Format(conn, "db2")
});
db2.DbMaintenance.CreateDatabase();

2. Dynamic table creation

The following code will generate two raw Order1 and Order2 table 

// Note that must share the same context db 
var db = new new SqlSugarClient ( new new ConnectionConfig () 
{ 
the DbType = SqlSugar.DbType.SqlServer, 
the ConnectionString = " ;. XXX " , 
InitKeyType = InitKeyType .Attribute // This attribute must be set like this 

)); 

db.MappingTables.Add( typeof (Order).Name, typeof (Order).Name + 1 ); 
db.CodeFirst.InitTables( typeof (Order)); 
db.MappingTables .Add( typeof (Order).Name, typeof(Order).Name + 2);
db.CodeFirst.InitTables(typeof(Order));

3. Add, delete, check and modify entities

var . db.Queryable List = <the Order> () the AS ( " order1 " ) .ToList (); // look-up table of order1
 // deletions and queries use the same method Inasertable () AS Deleteable () AS Updateable ().. .As

4. Cross-database table query

var list = db.Queryable<Order, OrderItem, Custom>((o, i, c) => o.Id == i.OrderId&&c.Id == o.CustomId)
.AS("xx.order")
.AS<OrderItem>("yy.OrderItem")
.AS<Custom>("zz.Custom")
.Select<ViewOrder>()
.ToList();

5. Multiple switching

SqlSugarClient db = new SqlSugarClient(new List<ConnectionConfig>()
{
new ConnectionConfig(){ ConfigId="1", DbType=DbType.SqlServer, 
ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
new ConnectionConfig(){ ConfigId="2", DbType=DbType.MySql, 
ConnectionString=Config.ConnectionString4 ,InitKeyType=InitKeyType.Attribute ,IsAutoCloseConnection=true}
});

//库1
try
{
db.BeginTran();
db.Deleteable<Order>().ExecuteCommand();

db.ChangeDatabase("2");//使用库2
db.Deleteable<Order>().ExecuteCommand();


db.CommitTran();
}
catch
{
db.RollbackTran();
}

 

Practice function 5: Unlimited levels of cascading insertion

Use sqlsugar only need to configure the primary key, do not need to configure any foreign key relationship to achieve cascading insertion

// foreign key automatically assigned 
db.Insertable ( new new the Order () 
{ 
    the Name = " line. 1 " , 
        CustomID = . 1 , 
        Price = 100 , 
        CreateTime = the DateTime.Now, 
        Id = 0 , // auto-increment 
        the Items = new new List<OrderItem> () {
                 new OrderItem(){ 
                    CreateTime = DateTime.Now, 
                    OrderId = 0 ,// Need to automatically get the auto- 
    increment column of the order 
                    Price = 1 , 
                    ItemId = 1 
                } 
            ) 
    )) .AddSubList(it => it.Items.First().OrderId) // Set the OrderId of the item table to be equal to the order auto-
 increment column     . ExecuteReturnPrimaryKey();
 

 

Practice function 6: fully automatic secondary cache

When we use Redis and other operations, it will become very complicated to clean up the cache in time when updating data. SqlSugar supports multi-table cache, and updates one of the tables and can clear the cache

The second cache cache is to cache the result set, read data from the cache when the SQL and parameters do not change, reducing the read and write operations of the database

ICacheService myCache = new HttpRuntimeCache(); 

  SqlSugarClient db = new SqlSugarClient( new ConnectionConfig() 

  { 

                ConnectionString = Config.ConnectionString, 

                DbType = DbType.SqlServer, 

                IsAutoCloseConnection = true , 

                ConfigureExternalServices = new ConfigureExternalServices() 

                { 

                    DataInfoCacheService = myCache // Configure us to create Cache class 

                } 

   });

db.Queryable <Student>().Where(it => it.Id> 0 ).WithCache().ToList(); // Set the default cache for one day 

db.Queryable <Student>().WithCache( 1000 ).ToList (); // Set specific expiration time

 

Delete data and update the cache at the same time, the same usage for insert and update

db.Deleteable<Student>().RemoveDataCache().Where(it => it.Id == 1 ).ExecuteCommand(); 

// remove all caches that reference the Student table, including multi-table queries

 

 

Practice function 7: Support multiple operations on the database

name Remarks Return type
GetDataBaseList Get all database names List
GetViewInfoList Get all views List
GetTableInfoList Get all tables List
GetColumnInfosByTableName Get columns based on table name List
GetIsIdentities Get auto-increment List
GetPrimaries Get primary key List
IsAnyTable Whether the table exists bool
IsAnyColumn Whether the column exists bool
IsPrimaryKey Whether the primary key exists bool
Identity Does self-increment exist bool
IsAnyConstraint Whether the constraint exists bool
DropTable Delete table bool
TruncateTable Empty table bool
CreateTable Create columns (not recommended, use CodeFirst to build tables) bool
AddColumn Add column bool
UpdateColumn Update column bool
AddPrimaryKey Add primary key bool
DropConstraint Delete constraint bool
BackupDataBase Backup library bool
DropColumn Delete column bool
RenameColumn Rename column bool
AddTableRemark Add table description bool
AddColumnRemark Add column description bool
DeleteColumnRemark Delete column description bool
RenameTable Rename table bool

 

Practice function 8: Dynamic SQL perfect anti-injection solution

var orderField = "order';drop table order";
var orderInfo= db.EntityMaintenance.GetEntityInfo<Order>();
 if (orderInfo.Columns.Any(it => it.DbColumnName != orderField)) 
{
    throw new Exception("请不要非法注入");
}
 db.Queryable<Order>().OrderBy(orderField).ToList();

 

SqlSugar has been working hard to make it better. All functions come from customers and have undergone long-term user practice, in order to be able to give me more motivation

 

Original code download:  https://github.com/sunkaixuan/SqlSugar 

                    https://gitee.com/sunkaixuan/SqlSugar

  

Guess you like

Origin www.oschina.net/news/121541/sqlsugar-orm-released