一、讀取數據庫鏈接數據庫
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;
}c#
二、定義別名app
[SugarTable(
"ado.Student"
)]
//別名處理
ide
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()spa
db.MappingColumns.Add() db.IgnoreColumns.Add()
咱們還能夠用AScode
//別名表 db.Queryable<T>().As("tableName").ToList(); //別名列 .Where(it=>SqlFunc.MappingColumn(it.OldName,"NewName") == "jack")
他們之間的優先級:orm
AS>Add>屬性方式ci
三、小技巧get
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();
四、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();
五、多個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();
六、MappingColumn 實現複雜的功能
var
s2 = db.Queryable<Student>()
.Select(it =>
new
{ id = it.Id, rowIndex=SqlFunc.MappingColumn(it.Id,
" row_number() over(order by id)"
) }).ToList();
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();
八、分組返回全部列
var file = db.Queryable<QRFileEntity>().PartitionBy(c => c.FName).Select(c => c).ToList();
九、聯表更新
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();