1、读取数据库连接

private SqlSugarClient GetInstance()
{
string conmstring = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["BaseDb"].ToString();
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { InitKeyType = InitKeyType.Attribute, ConnectionString = conmstring, DbType = SqlSugar.DbType.SqlServer, IsAutoCloseConnection = true });
return db;
}

 

2、定义别名

[SugarTable("ado.Student")] //别名处理

public class Student {

 

[SugarColumn(IsIgnore=true)]


public string xxx{get;set;} //这列在ORM会过滤掉

 

[SugarColumn(ColumnName="name")]


public string xxx{get;set;} //这列在ORM会当成 name处理

}

我们可以用Add的方式

db.MappingTables.Add()

db.MappingColumns.Add()
db.IgnoreColumns.Add()

我们还可以用AS

//别名表
db.Queryable<T>().As("tableName").ToList();

//别名列
.Where(it=>SqlFunc.MappingColumn(it.OldName,"NewName") == "jack")

他们之间的优先级:

AS>Add>属性方式

 

3、小技巧

Queryable<T>().AS("(select * from [student]) t").ToPageList(1,2);

使用函数 SqlFunc类


var getByFuns = db.Queryable<Student>().Where(it => SqlFunc.IsNullOrEmpty(it.Name)).ToList();


是否存在这条记录

var isAny2 = db.Queryable<Student>().Any(it => it.Id == -1);
获取同一天的记录 

var getTodayList = db.Queryable<Student>().Where(it => SqlFunc.DateIsSame(it.CreateTime, DateTime.Now)).ToList();

4、IN查询

var in1 = db.Queryable<Student>().In(it=>it.Id,new int[] { 1, 2, 3 }).ToList();

var in1 = db.Queryable<Student>().In(it=>it.Id,new int[] { 1, 2, 3 }).ToList();

5、多个Queryable

var q1= db.Queryable<DataItemEntity, DataItemDetailEntity>((a, b) => new object[] {
JoinType.Left,a.ItemId==b.ItemId,
}).Select((a,b) => b);var q2 = db.Queryable<QRFileEntity>();
var innerjoin = db.Queryable(q1, q2, JoinType.Inner, (j1, j2) => j1.ItemDetailId == j2.ParentId).Select((j1, j2) => j1).ToList();

6、MappingColumn 实现复杂的功能

var s2 = db.Queryable<Student>()

.Select(it => new { id = it.Id, rowIndex=SqlFunc.MappingColumn(it.Id, " row_number() over(order by id)") }).ToList();

 

7、列明动态查询

var propertyName = "ItemDetailId'"; //类中的属性的名称
var dbColumnName = db.EntityProvider.GetDbColumnName<DataItemDetailEntity>(propertyName);
var list2 = db.Ado.SqlQuery<DataItemDetailEntity>(string.Format("select * from DataItemDetail where {0} =@value ", dbColumnName), new { value =""}).ToList();

 

8、分组返回所有列

var file = db.Queryable<QRFileEntity>().PartitionBy(c => c.FName).Select(c => c).ToList();

9、联表更新

var res = db.Updateable<QRFileEntity>().UpdateColumns(c => new QRFileEntity
{
  CreateUserName = SqlFunc.Subqueryable<UserEntity>().Where(d => d.UserId == "").Select(d => d.RealName),
  FName = ""
}).Where(c => c.FileId == "").ExecuteCommand();