SqlSugar源码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

375 lines
12 KiB

7 years ago
4 years ago
## 👨‍🎓果糖大数据科技(南通)有限公司(永久免费开源) ##
4 years ago
公司地址:南通太阳晶城大厦3幢125室
4 years ago
4 years ago
| qq | 微信 | Email | QQ Group |
4 years ago
| ---------| ---------| ---------| ---------|
| 610262374 | sabimao | 610262374@qq.com | 225982985 |
4 years ago
4 years ago
服务项目:接收项目外包等服务(高级程序员 & 需求分析 & 软件架构师),技术咨询,技术顾问
5 years ago
4 years ago
## 👮‍♀️中文文档:
4 years ago
4 years ago
世界上最简单的ORM,只需要配置连接字符串,F5运行控制台自动建库建表运行DEMO
4 years ago
4 years ago
<font color=#0099ff size=72> 地址:</font> http://donet5.com/Home/Doc
4 years ago
4 years ago
4 years ago
# 🕵️‍♀️English documents
4 years ago
4 years ago
Using SqlSugar is very simple , And it's powerful.
6 years ago
6 years ago
SqlSugar=One object+One parameter=16 functions,
7 years ago
4 years ago
Support:MySql、SqlServer、Sqlite、Oracle 、 postgresql 、达梦、人大金仓
4 years ago
8 years ago
4 years ago
## 📮Nuget
6 years ago
|.net |.net core |
|---------| ---------|
|Install-Package sqlSugar |Install-Package sqlSugarCore|
4 years ago
## 📑SqlSugar's 16 Functions
6 years ago
There are 16 methods under SqlSugarClient
4 years ago
![输入图片说明](http://www.donet5.com/_theme/ueditor/utf8-net/net/upload/image/20190430/6369224056499802674782957.jpg?id=111 "sqlsugar")
6 years ago
4 years ago
## 🎀 Create SqlSugarClient
5 years ago
All operations are based on SqlSugarClient
6 years ago
6 years ago
SqlSugarClient parameter and only one ConnectionConfig
6 years ago
```cs
4 years ago
public List<Student> GetStudentList()
6 years ago
{
4 years ago
var db = GetInstance();
var list = db.Queryable<Student>().ToList();//Search
6 years ago
return list;
}
6 years ago
6 years ago
/// <summary>
/// Create SqlSugarClient
/// </summary>
/// <returns></returns>
private SqlSugarClient GetInstance()
{
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
4 years ago
{
ConnectionString = "Server=.xxxxx",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
6 years ago
//Print sql
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
Console.WriteLine();
};
return db;
}
6 years ago
6 years ago
public class Student
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
6 years ago
public int Id { get; set; }
public int? SchoolId { get; set; }
public string Name { get; set; }
}
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/0.SqlSugarClient)
4 years ago
7 years ago
4 years ago
## 🎉 1. Queryable
6 years ago
We use it to query
4 years ago
![输入图片说明](http://www.donet5.com/_theme/ueditor/utf8-net/net/upload/image/20190502/6369240932997363035197459.png?id=1112 "Queryable")
4 years ago
Here are some examples
```cs
6 years ago
//easy
8 years ago
var getAll = db.Queryable<Student>().ToList();
var getAllNoLock = db.Queryable<Student>().With(SqlWith.NoLock).ToList();
var getByPrimaryKey = db.Queryable<Student>().InSingle(2);
4 years ago
var sum = db.Queryable<Student>().Sum(it => it.Id);
var isAny = db.Queryable<Student>().Where(it => it.Id == -1).Any();
8 years ago
var isAny2 = db.Queryable<Student>().Any(it => it.Id == -1);
var getListByRename = db.Queryable<School>().AS("Student").ToList();
6 years ago
var getByWhere = db.Queryable<Student>().Where(it => it.Id == 1 || it.Name == "a").ToList();
var getByFuns = db.Queryable<Student>().Where(it => SqlFunc.IsNullOrEmpty(it.Name)).ToList();
4 years ago
var group = db.Queryable<Student>().GroupBy(it => it.Id).Select(it => new { id = SqlFunc.AggregateCount(it.Id) }).ToList();
8 years ago
6 years ago
//Page
8 years ago
var page = db.Queryable<Student>().ToPageList(pageIndex, pageSize, ref totalCount);
8 years ago
8 years ago
//page join
4 years ago
var pageJoin = db.Queryable<Student, School>((st, sc) => new JoinQueryInfos(JoinType.Left, st.SchoolId == sc.Id))
6 years ago
.ToPageList(pageIndex, pageSize, ref totalCount);
8 years ago
8 years ago
//top 5
var top5 = db.Queryable<Student>().Take(5).ToList();
8 years ago
8 years ago
//join Order By (order by st.id desc,sc.id desc)
4 years ago
var list4 = db.Queryable<Student, School>((st, sc) => new JoinQueryInfos(JoinType.Left, st.SchoolId == sc.Id))
.OrderBy(st => st.Id, OrderByType.Desc)
.OrderBy((st, sc) => sc.Id, OrderByType.Desc)
6 years ago
.Select<ViewModelStudent>().ToList();
8 years ago
7 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/1.Queryable)
6 years ago
6 years ago
4 years ago
## 🎊 2. Updateable
6 years ago
We use it to Update
6 years ago
```cs
//update reutrn Update Count
var t1= db.Updateable(updateObj).ExecuteCommand();
//Only update Name
var t3 = db.Updateable(updateObj).UpdateColumns(it => new { it.Name }).ExecuteCommand();
//Ignore Name and TestId
var t4 = db.Updateable(updateObj).IgnoreColumns(it => new { it.Name, it.TestId }).ExecuteCommand();
//update List<T>
var t7 = db.Updateable(updateObjs).ExecuteCommand();
//Where By Expression
4 years ago
var t9 = db.Updateable(it => new class() { name = "a",createtime = p }).Where(it => it.Id == 1).ExecuteCommand();
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/2.Updateable)
8 years ago
4 years ago
4 years ago
## 🎃 3. Insertable
6 years ago
We use it to Insert
```cs
8 years ago
//Insert reutrn Insert Count
var t2 = db.Insertable(insertObj).ExecuteCommand();
8 years ago
8 years ago
//Insert reutrn Identity Value
var t3 = db.Insertable(insertObj).ExecuteReutrnIdentity();
8 years ago
8 years ago
//Only insert Name
4 years ago
var t4 = db.Insertable(insertObj).InsertColumns(it => new { it.Name, it.SchoolId }).ExecuteReutrnIdentity();
8 years ago
8 years ago
//Ignore TestId
var t5 = db.Insertable(insertObj).IgnoreColumns(it => new { it.Name, it.TestId }).ExecuteReutrnIdentity();
//Insert List<T>
6 years ago
var s9 = db.Insertable(insertObjs).InsertColumns(it => new { it.Name }).ExecuteCommand();
8 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/3.Insertable)
4 years ago
4 years ago
## 🎄 4. Deleteable
6 years ago
We use it to Delete
8 years ago
```cs
6 years ago
//by entity
db.Deleteable<Student>().Where(new Student() { Id = 1 }).ExecuteCommand();
8 years ago
//by primary key
6 years ago
db.Deleteable<Student>().In(1).ExecuteCommand();
8 years ago
//by primary key array
6 years ago
db.Deleteable<Student>().In(new int[] { 1, 2 }).ExecuteCommand();
8 years ago
//by expression
6 years ago
db.Deleteable<Student>().Where(it => it.Id == 1).ExecuteCommand();
6 years ago
8 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/4.Deleteable )
8 years ago
4 years ago
## 🎋 5. SqlQueryable
6 years ago
```cs
var list = db.SqlQueryable<Student>("select * from student").ToPageList(1, 2);
4 years ago
var list2 = db.SqlQueryable<Student>("select * from student").Where(it => it.Id == 1).ToPageList(1, 2);
var list3 = db.SqlQueryable<Student>("select * from student").Where("id=@id", new { id = 1 }).ToPageList(1, 2);
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/5.SqlQueryable )
4 years ago
## 🎎 6. SaveQueues
6 years ago
Perform multiple operations together with transactions
```cs
var db = GetInstance();
db.Insertable<Student>(new Student() { Name = "a" }).AddQueue();
db.Insertable<Student>(new Student() { Name = "b" }).AddQueue();
4 years ago
db.SaveQueues();
6 years ago
db.Insertable<Student>(new Student() { Name = "a" }).AddQueue();
db.Insertable<Student>(new Student() { Name = "b" }).AddQueue();
db.Insertable<Student>(new Student() { Name = "c" }).AddQueue();
db.Insertable<Student>(new Student() { Name = "d" }).AddQueue();
4 years ago
var ar = db.SaveQueuesAsync();
6 years ago
db.Queryable<Student>().AddQueue();
db.Queryable<School>().AddQueue();
4 years ago
db.AddQueue("select * from student where id=@id", new { id = 1 });
6 years ago
var result2 = db.SaveQueues<Student, School, Student>();
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/6.queue )
6 years ago
4 years ago
## 🎫 7.Ado
6 years ago
db.Ado.MethodName,Look at the following example
```cs
var dt=db.Ado.GetDataTable("select * from table where id=@id and name=@name",new List<SugarParameter>(){
new SugarParameter("@id",1),
new SugarParameter("@name",2)
});
4 years ago
var dt = db.Ado.GetDataTable("select * from table where id=@id and name=@name", new { id = 1, name = 2 });
6 years ago
//Use Stored Procedure
4 years ago
var dt2 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", new { name = "张三", age = 0 });// GetInt SqlQuery<T> 等等都可以用
var nameP = new SugarParameter("@name", "张三");
var ageP = new SugarParameter("@age", null, true);//isOutput=true
var dt2 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", nameP, ageP);
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/7.ado )
4 years ago
## 🧶 8.Saveable
6 years ago
Insert or Update
```cs
db.Saveable<Student>(entity).ExecuteReturnEntity();
db.Saveable<Student>(new Student() { Name = "" })
4 years ago
.InsertColumns(it => it.Name)
.UpdateColumns(it => new { it.Name, it.CreateTime }
6 years ago
.ExecuteReturnEntity();
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/8.saveable )
6 years ago
4 years ago
## 🛒 9.EntityMain
6 years ago
```cs
var entityInfo=db.EntityMaintenance.GetEntityInfo<Student>();
foreach (var column in entityInfo.Columns)
{
Console.WriteLine(column.ColumnDescription);
}
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/9.entityMain )
4 years ago
## 🥼 10.DbMain
6 years ago
```cs
var tables = db.DbMaintenance.GetTableInfoList();
4 years ago
foreach (var table in tables)
{
Console.WriteLine(table.Description);
}
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/a.DbMain )
6 years ago
4 years ago
## 🦺 11.Aop
```cs
4 years ago
db.Aop.OnLogExecuted = (sql, pars) => //SQL executed event
7 years ago
{
4 years ago
6 years ago
};
4 years ago
db.Aop.OnLogExecuting = (sql, pars) => //SQL executing event (pre-execution)
6 years ago
{
4 years ago
6 years ago
};
4 years ago
db.Aop.OnError = (exp) =>//SQL execution error event
6 years ago
{
4 years ago
6 years ago
};
4 years ago
db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL executing event (pre-execution,SQL script can be modified)
6 years ago
{
4 years ago
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
6 years ago
};
8 years ago
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/b.aop )
6 years ago
4 years ago
## 🎁 12.QueryFilter
6 years ago
```cs
6 years ago
4 years ago
//gobal filter
6 years ago
var db = GetInstance();
var sql = db.Queryable<Student>().ToSql();
//SELECT [ID],[SchoolId],[Name],[CreateTime] FROM [STudent] WHERE isDelete=0
6 years ago
6 years ago
public static SqlSugarClient GetInstance()
{
4 years ago
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { xxx);
db.QueryFilter.Add(new SqlFilterItem()
{
FilterValue = filterDb =>
{
return new SqlFilterResult() { Sql = " isDelete=0" };
}
});
return db;
6 years ago
}
6 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/c.GobalFilter )
4 years ago
## 🍔 13.DbFirst
6 years ago
```cs
8 years ago
var db = GetInstance();
//Create all class
db.DbFirst.CreateClassFile("c:\\Demo\\1");
8 years ago
//Create student calsss
db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2");
//Where(array)
8 years ago
//Mapping name
db.MappingTables.Add("ClassStudent", "Student");
db.MappingColumns.Add("NewId", "Id", "ClassStudent");
db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\3");
8 years ago
//Remove mapping
db.MappingTables.Clear();
8 years ago
//Create class with default value
db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\Demo\\4", "Demo.Models");
8 years ago
//Mapping and Attribute
db.MappingTables.Add("ClassStudent", "Student");
db.MappingColumns.Add("NewId", "Id", "ClassStudent");
db.DbFirst.IsCreateAttribute().Where("Student").CreateClassFile("c:\\Demo\\5");
8 years ago
8 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/d.DbFirst )
4 years ago
## 🥙 14.CodeFirst
```cs
4 years ago
db.CodeFirst.SetStringDefaultLength(100).BackupTable().InitTables(typeof(CodeTable), typeof(CodeTable2)); //change entity backupTable
6 years ago
db.CodeFirst.SetStringDefaultLength(100).InitTables(typeof(CodeTable), typeof(CodeTable2));
7 years ago
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/e.CodeFirst )
4 years ago
## 🧈1 5.Utilities
6 years ago
```cs
var list = db.Utilities.DataTableToList(datatable);
```
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/f.Utilities )
6 years ago
4 years ago
## 🥫 16.SimpleClient
6 years ago
```cs
6 years ago
var db = GetInstance();
var sdb = db.GetSimpleClient<Student>();
sdb.GetById(1);
sdb.GetList();
sdb.DeleteById(1);
sdb.Update(obj);
```
6 years ago
6 years ago
[<font color=red>View more >> </font>](https://github.com/sunkaixuan/SqlSugar/wiki/g.SimpleClient )
4 years ago
7 years ago
4 years ago
## 🕹 Code generator
6 years ago
https://github.com/sunkaixuan/SoEasyPlatform
4 years ago