mirror of
https://gitee.com/dotnetchina/SqlSugar.git
synced 2025-08-23 13:06:50 +08:00
Update TDengine
This commit is contained in:
parent
07e20bb53e
commit
0534b0661d
@ -6,7 +6,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="TDengine.Ado.Data" Version="1.4.0" />
|
||||
<PackageReference Include="TDengine.Ado.Data" Version="1.6.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
@ -7,84 +7,9 @@ namespace SqlSugar.TDengine
|
||||
{
|
||||
public class TDengineCodeFirst : CodeFirstProvider
|
||||
{
|
||||
protected override void ExistLogicEnd(List<EntityColumnInfo> dbColumns)
|
||||
{
|
||||
foreach (EntityColumnInfo column in dbColumns)
|
||||
{
|
||||
if (column.DefaultValue != null)
|
||||
{
|
||||
this.Context.DbMaintenance.AddDefaultValue(column.DbTableName,column.DbColumnName,column.DefaultValue.ToSqlValue());
|
||||
}
|
||||
}
|
||||
}
|
||||
public override void NoExistLogic(EntityInfo entityInfo)
|
||||
{
|
||||
var tableName = GetTableName(entityInfo);
|
||||
//Check.Exception(entityInfo.Columns.Where(it => it.IsPrimarykey).Count() > 1, "Use Code First ,The primary key must not exceed 1");
|
||||
List<DbColumnInfo> columns = new List<DbColumnInfo>();
|
||||
if (entityInfo.Columns.HasValue())
|
||||
{
|
||||
foreach (var item in entityInfo.Columns.Where(it=>it.IsIgnore==false))
|
||||
{
|
||||
DbColumnInfo dbColumnInfo = this.EntityColumnToDbColumn(entityInfo, tableName, item);
|
||||
columns.Add(dbColumnInfo);
|
||||
}
|
||||
if (entityInfo.IsCreateTableFiledSort)
|
||||
{
|
||||
columns = columns.OrderBy(c => c.CreateTableFieldSort).ToList();
|
||||
}
|
||||
}
|
||||
columns = columns.OrderBy(it => it.IsPrimarykey ? 0 : 1).ToList();
|
||||
this.Context.DbMaintenance.CreateTable(tableName, columns,true);
|
||||
throw new NotSupportedException("TDengine 暂时不支持CodeFirst等方法还在开发");
|
||||
}
|
||||
protected override DbColumnInfo EntityColumnToDbColumn(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
|
||||
{
|
||||
var propertyType = UtilMethods.GetUnderType(item.PropertyInfo);
|
||||
var result = new DbColumnInfo()
|
||||
{
|
||||
TableId = entityInfo.Columns.IndexOf(item),
|
||||
DbColumnName = item.DbColumnName.HasValue() ? item.DbColumnName : item.PropertyName,
|
||||
IsPrimarykey = item.IsPrimarykey,
|
||||
IsIdentity = item.IsIdentity,
|
||||
TableName = tableName,
|
||||
IsNullable = item.IsNullable,
|
||||
DefaultValue = item.DefaultValue,
|
||||
ColumnDescription = item.ColumnDescription,
|
||||
Length = item.Length,
|
||||
CreateTableFieldSort = item.CreateTableFieldSort
|
||||
};
|
||||
if (propertyType == UtilConstants.DecType)
|
||||
{
|
||||
result.Scale = item.DecimalDigits;
|
||||
result.DecimalDigits = item.DecimalDigits;
|
||||
}
|
||||
GetDbType(item, propertyType, result);
|
||||
if (result.DataType.Equals("varchar", StringComparison.CurrentCultureIgnoreCase) && result.Length == 0)
|
||||
{
|
||||
result.Length = 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
protected override void ConvertColumns(List<DbColumnInfo> dbColumns)
|
||||
{
|
||||
foreach (var item in dbColumns)
|
||||
{
|
||||
if (item.DataType == "DateTime")
|
||||
{
|
||||
item.Length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override void ChangeKey(EntityInfo entityInfo, string tableName, EntityColumnInfo item)
|
||||
{
|
||||
this.Context.DbMaintenance.UpdateColumn(tableName, EntityColumnToDbColumn(entityInfo, tableName, item));
|
||||
if (!item.IsPrimarykey)
|
||||
this.Context.DbMaintenance.DropConstraint(tableName,null);
|
||||
if (item.IsPrimarykey)
|
||||
this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -19,35 +19,7 @@ namespace SqlSugar.TDengine
|
||||
{
|
||||
get
|
||||
{
|
||||
string schema = GetSchema();
|
||||
string sql = @"select cast (pclass.oid as int4) as TableId,cast(ptables.tablename as varchar) as TableName,
|
||||
pcolumn.column_name as DbColumnName,pcolumn.udt_name as DataType,
|
||||
CASE WHEN pcolumn.numeric_scale >0 THEN pcolumn.numeric_precision ELSE pcolumn.character_maximum_length END as Length,
|
||||
pcolumn.column_default as DefaultValue,
|
||||
pcolumn.numeric_scale as DecimalDigits,
|
||||
pcolumn.numeric_scale as Scale,
|
||||
col_description(pclass.oid, pcolumn.ordinal_position) as ColumnDescription,
|
||||
case when pkey.colname = pcolumn.column_name
|
||||
then true else false end as IsPrimaryKey,
|
||||
case when pcolumn.column_default like 'nextval%'
|
||||
then true else false end as IsIdentity,
|
||||
case when pcolumn.is_nullable = 'YES'
|
||||
then true else false end as IsNullable
|
||||
from (select * from pg_tables where upper(tablename) = upper('{0}') and schemaname='" + schema + @"') ptables inner join pg_class pclass
|
||||
on ptables.tablename = pclass.relname inner join (SELECT *
|
||||
FROM information_schema.columns
|
||||
) pcolumn on pcolumn.table_name = ptables.tablename
|
||||
left join (
|
||||
select pg_class.relname,pg_attribute.attname as colname from
|
||||
pg_constraint inner join pg_class
|
||||
on pg_constraint.conrelid = pg_class.oid
|
||||
inner join pg_attribute on pg_attribute.attrelid = pg_class.oid
|
||||
and pg_attribute.attnum = pg_constraint.conkey[1]
|
||||
inner join pg_type on pg_type.oid = pg_attribute.atttypid
|
||||
where pg_constraint.contype='p'
|
||||
) pkey on pcolumn.table_name = pkey.relname
|
||||
order by table_catalog, table_schema, ordinal_position";
|
||||
return sql;
|
||||
throw new NotSupportedException("TDengineCode暂时不支持DbFirst等方法,还在开发");
|
||||
}
|
||||
}
|
||||
|
||||
@ -212,7 +184,7 @@ namespace SqlSugar.TDengine
|
||||
{
|
||||
get
|
||||
{
|
||||
return "select 1 from information_schema.columns limit 1 offset 0";
|
||||
throw new NotSupportedException("TDengine 暂时不支持DbFirst等方法,还在开发");
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
@ -10,14 +10,14 @@ namespace SqlSugar.TDengine
|
||||
{
|
||||
get
|
||||
{
|
||||
return "\"";
|
||||
return "`";
|
||||
}
|
||||
}
|
||||
public override string SqlTranslationRight
|
||||
{
|
||||
get
|
||||
{
|
||||
return "\"";
|
||||
return "`";
|
||||
}
|
||||
}
|
||||
public override string SqlDateNow
|
||||
@ -80,7 +80,7 @@ namespace SqlSugar.TDengine
|
||||
var mappingInfo = context
|
||||
.MappingTables
|
||||
.FirstOrDefault(it => it.EntityName.Equals(name, StringComparison.CurrentCultureIgnoreCase));
|
||||
if (mappingInfo == null && name.Contains(".") && name.Contains("\""))
|
||||
if (mappingInfo == null && name.Contains(".") && name.Contains("`"))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
|
@ -13,14 +13,14 @@ namespace SqlSugar.TDengine
|
||||
{
|
||||
get
|
||||
{
|
||||
return "\"";
|
||||
return "`";
|
||||
}
|
||||
}
|
||||
public override string SqlTranslationRight
|
||||
{
|
||||
get
|
||||
{
|
||||
return "\"";
|
||||
return "`";
|
||||
}
|
||||
}
|
||||
public override string GetTranslationText(string name)
|
@ -15,14 +15,14 @@ namespace SqlSugar.TDengine
|
||||
return @"INSERT INTO {0}
|
||||
({1})
|
||||
VALUES
|
||||
({2}) returning $PrimaryKey";
|
||||
({2}) ";
|
||||
}
|
||||
else
|
||||
{
|
||||
return @"INSERT INTO {0}
|
||||
({1})
|
||||
VALUES
|
||||
({2}) ;";
|
||||
({2})";
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -76,7 +76,7 @@ namespace SqlSugar.TDengine
|
||||
}
|
||||
public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command)
|
||||
{
|
||||
((TDengineDataAdapter)dataAdapter).SelectCommand = (TDengineCommand)command;
|
||||
((SqlSugar.TDengineCore.TDengineDataAdapter)dataAdapter).SelectCommand = (TDengineCommand)command;
|
||||
}
|
||||
/// <summary>
|
||||
/// if mysql return MySqlParameter[] pars
|
||||
@ -94,7 +94,7 @@ namespace SqlSugar.TDengine
|
||||
if (parameter.Value == null) parameter.Value = DBNull.Value;
|
||||
|
||||
var sqlParameter = new TDengineParameter(parameter.ParameterName,parameter.Value,parameter.DbType,0);
|
||||
result[0]=sqlParameter;
|
||||
result[i]=sqlParameter;
|
||||
i++;
|
||||
}
|
||||
return result;
|
||||
|
@ -6,6 +6,8 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using SqlSugar;
|
||||
using TDengineDriver;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo0_SqlSugarClient
|
||||
@ -13,49 +15,10 @@ namespace OrmTest
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
SqlSugarClient();//Create db
|
||||
DbContext();//Optimizing SqlSugarClient usage
|
||||
SingletonPattern();//Singleten Pattern
|
||||
DistributedTransactionExample();
|
||||
MasterSlave();//Read-write separation
|
||||
CustomAttribute();
|
||||
}
|
||||
|
||||
private static void MasterSlave()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### MasterSlave Start ####");
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
var db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
ConnectionString = Config.ConnectionString,//Master Connection
|
||||
DbType = DbType.TDengine,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
|
||||
new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 } ,
|
||||
new SlaveConnectionConfig() { HitRate=10, ConnectionString=Config.ConnectionString2 }
|
||||
}
|
||||
});
|
||||
db.Aop.OnLogExecuted = (s, p) =>
|
||||
{
|
||||
Console.WriteLine(db.Ado.Connection.ConnectionString);
|
||||
};
|
||||
Console.WriteLine("Master:");
|
||||
db.Insertable(new Order() { Name = "abc", CustomId = 1, CreateTime = DateTime.Now }).ExecuteCommand();
|
||||
Console.WriteLine("Slave:");
|
||||
db.Queryable<Order>().First();
|
||||
Console.WriteLine("#### MasterSlave End ####");
|
||||
}
|
||||
|
||||
private static void SqlSugarClient()
|
||||
{
|
||||
//Create db
|
||||
Console.WriteLine("#### SqlSugarClient Start ####");
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
DbType = SqlSugar.DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
@ -67,356 +30,51 @@ namespace OrmTest
|
||||
}
|
||||
});
|
||||
|
||||
//If no exist create datebase
|
||||
db.DbMaintenance.CreateDatabase();
|
||||
//建库
|
||||
db.Ado.ExecuteCommand("CREATE DATABASE IF NOT EXISTS power WAL_RETENTION_PERIOD 3600");
|
||||
|
||||
//Use sql
|
||||
var dt = db.Ado.ExecuteCommand("SET GLOBAL local_infile=1");
|
||||
//建超级表
|
||||
db.Ado.ExecuteCommand("CREATE STABLE IF NOT EXISTS MyTable (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (location BINARY(64), groupId INT)");
|
||||
|
||||
//Create tables
|
||||
db.CodeFirst.InitTables(typeof(OrderItem),typeof(Order));
|
||||
var id = db.Insertable(new Order() { Name = "order1", CustomId = 1, Price = 0, CreateTime = DateTime.Now }).ExecuteReturnIdentity();
|
||||
//创建子表
|
||||
db.Ado.ExecuteCommand(@"create table IF NOT EXISTS MyTable01 using MyTable tags('California.SanFrancisco',1)");
|
||||
|
||||
//Insert data
|
||||
db.Insertable(new OrderItem() { OrderId = id, Price = 0, CreateTime=DateTime.Now }).ExecuteCommand();
|
||||
Console.WriteLine("#### SqlSugarClient End ####");
|
||||
|
||||
//insert sql
|
||||
//db.Ado.ExecuteCommand(insrtSql);
|
||||
|
||||
//查询子表
|
||||
var dt = db.Ado.GetDataTable("select * from MyTable01");
|
||||
|
||||
//查询超级表
|
||||
var dt2 = db.Ado.GetDataTable("select * from MyTable");
|
||||
|
||||
db.Insertable(new MyTable01()
|
||||
{
|
||||
ts = DateTime.Now,
|
||||
current = Convert.ToSingle(1.1),
|
||||
groupId = 1,
|
||||
location = "aa",
|
||||
phase = Convert.ToSingle(1.1),
|
||||
voltage = 11
|
||||
}).ExecuteCommand();
|
||||
|
||||
var list = db.Queryable<MyTable01>().ToList();
|
||||
}
|
||||
|
||||
private static void DbContext()
|
||||
public class MyTable01
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### DbContext Start ####");
|
||||
var insertObj = new Order { Name = "jack", CreateTime = DateTime.Now };
|
||||
var InsertObjs = new Order[] { insertObj };
|
||||
|
||||
DbContext context = new DbContext();
|
||||
|
||||
context.Db.CodeFirst.InitTables<Order, OrderItem,Custom>();//Create Tables
|
||||
;
|
||||
var orderDb = context.OrderDb;
|
||||
|
||||
//Select
|
||||
var data1 = orderDb.GetById(1);
|
||||
var data2 = orderDb.GetList();
|
||||
var data3 = orderDb.GetList(it => it.Id == 1);
|
||||
var data4 = orderDb.GetSingle(it => it.Id == 1);
|
||||
var p = new PageModel() { PageIndex = 1, PageSize = 2 };
|
||||
var data5 = orderDb.GetPageList(it => it.Name == "xx", p);
|
||||
Console.Write(p.TotalCount);
|
||||
var data6 = orderDb.GetPageList(it => it.Name == "xx", p, it => it.Name, OrderByType.Asc);
|
||||
Console.Write(p.TotalCount);
|
||||
List<IConditionalModel> conModels = new List<IConditionalModel>();
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
|
||||
var data7 = orderDb.GetPageList(conModels, p, it => it.Name, OrderByType.Asc);
|
||||
orderDb.AsQueryable().Where(x => x.Id == 1).ToList();
|
||||
|
||||
//Insert
|
||||
orderDb.Insert(insertObj);
|
||||
orderDb.InsertRange(InsertObjs);
|
||||
var id = orderDb.InsertReturnIdentity(insertObj);
|
||||
orderDb.AsInsertable(insertObj).ExecuteCommand();
|
||||
|
||||
|
||||
//Delete
|
||||
orderDb.Delete(insertObj);
|
||||
orderDb.DeleteById(11111);
|
||||
orderDb.DeleteById(new int[] { 1111, 2222 });
|
||||
orderDb.Delete(it => it.Id == 1111);
|
||||
orderDb.AsDeleteable().Where(it => it.Id == 1111).ExecuteCommand();
|
||||
|
||||
//Update
|
||||
orderDb.Update(insertObj);
|
||||
orderDb.UpdateRange(InsertObjs);
|
||||
orderDb.Update(it => new Order() { Name = "a", }, it => it.Id == 1);
|
||||
orderDb.AsUpdateable(insertObj).UpdateColumns(it => new { it.Name }).ExecuteCommand();
|
||||
|
||||
//Use Inherit DbContext
|
||||
OrderDal dal = new OrderDal();
|
||||
var data = dal.GetById(1);
|
||||
var list = dal.GetList();
|
||||
|
||||
Console.WriteLine("#### DbContext End ####");
|
||||
}
|
||||
|
||||
private static void CustomAttribute()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Custom Attribute Start ####");
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
ConnectionString = Config.ConnectionString,
|
||||
DbType = DbType.TDengine,
|
||||
IsAutoCloseConnection = true,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
ConfigureExternalServices = new ConfigureExternalServices()
|
||||
{
|
||||
EntityService = (property, column) =>
|
||||
{
|
||||
|
||||
var attributes = property.GetCustomAttributes(true);//get all attributes
|
||||
|
||||
if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey
|
||||
{
|
||||
column.IsPrimarykey = true;
|
||||
}
|
||||
},
|
||||
EntityNameService = (type, entity) =>
|
||||
{
|
||||
var attributes = type.GetCustomAttributes(true);
|
||||
if (attributes.Any(it => it is TableAttribute))
|
||||
{
|
||||
entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
db.CodeFirst.InitTables<AttributeTable>();//Create Table
|
||||
|
||||
db.Insertable(new AttributeTable() { Id = Guid.NewGuid().ToString(), Name = "Name" }).ExecuteCommand();
|
||||
var list = db.Queryable<AttributeTable>().ToList();
|
||||
|
||||
Console.WriteLine("#### Custom Attribute End ####");
|
||||
public DateTime ts { get; set; }
|
||||
public float current { get; set; }
|
||||
public int voltage { get; set; }
|
||||
public float phase { get; set; }
|
||||
[SugarColumn(IsOnlyIgnoreInsert =true,IsOnlyIgnoreUpdate =true)]
|
||||
public string location { get; set; }
|
||||
[SugarColumn(IsOnlyIgnoreInsert = true, IsOnlyIgnoreUpdate = true)]
|
||||
public int groupId { get; set; }
|
||||
}
|
||||
|
||||
|
||||
private static void SingletonPattern()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Singleton Pattern Start ####");
|
||||
Console.WriteLine("Db_Id:" + singleDb.ContextID);
|
||||
Console.WriteLine("Db_Id:" + singleDb.ContextID);
|
||||
var task = new Task(() =>
|
||||
{
|
||||
Console.WriteLine("Task DbId:" + singleDb.ContextID);
|
||||
new Task(() =>
|
||||
{
|
||||
Console.WriteLine("_Task_Task DbId:" + singleDb.ContextID);
|
||||
Console.WriteLine("_Task_Task DbId:" + singleDb.ContextID);
|
||||
|
||||
}).Start();
|
||||
Console.WriteLine("Task DbId:" + singleDb.ContextID);
|
||||
});
|
||||
task.Start();
|
||||
task.Wait();
|
||||
System.Threading.Thread.Sleep(500);
|
||||
Console.WriteLine(string.Join(",", singleDb.TempItems.Keys));
|
||||
|
||||
Console.WriteLine("#### Singleton Pattern end ####");
|
||||
}
|
||||
|
||||
static SqlSugarScope singleDb = new SqlSugarScope(
|
||||
new ConnectionConfig()
|
||||
{
|
||||
ConfigId = 1,
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents()
|
||||
{
|
||||
OnLogExecuting = (sql, p) => { Console.WriteLine(sql); }
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
private static void DistributedTransactionExample()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Distributed TransactionExample Start ####");
|
||||
SqlSugarClient db = new SqlSugarClient(new List<ConnectionConfig>()
|
||||
{
|
||||
new ConnectionConfig(){ ConfigId="1", DbType=DbType.TDengine, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
|
||||
new ConnectionConfig(){ ConfigId="2", DbType=DbType.TDengine, ConnectionString=Config.ConnectionString2 ,InitKeyType=InitKeyType.Attribute ,IsAutoCloseConnection=true}
|
||||
});
|
||||
|
||||
var db1 = db.Ado.Connection.Database;
|
||||
//use db1
|
||||
db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order), typeof(OrderItem));//
|
||||
db.Insertable(new Order() { Name = "order1", CreateTime = DateTime.Now }).ExecuteCommand();
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType + ":" + db.Queryable<Order>().Count());
|
||||
|
||||
//use db2
|
||||
db.ChangeDatabase("2");
|
||||
var db2 = db.Ado.Connection.Database;
|
||||
db.DbMaintenance.CreateDatabase();//Create Database2
|
||||
db.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order), typeof(OrderItem));
|
||||
db.Insertable(new Order() { Name = "order1", CreateTime = DateTime.Now }).ExecuteCommand();
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType + ":" + db.Queryable<Order>().Count());
|
||||
|
||||
if (db2 == db1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Example 1
|
||||
Console.WriteLine("Example 1");
|
||||
try
|
||||
{
|
||||
db.BeginTran();
|
||||
|
||||
db.ChangeDatabase("1");//use db1
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
throw new Exception();
|
||||
db.CommitTran();
|
||||
}
|
||||
catch
|
||||
{
|
||||
db.RollbackTran();
|
||||
Console.WriteLine("---Roll back");
|
||||
db.ChangeDatabase("1");//use db1
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
}
|
||||
|
||||
|
||||
|
||||
// Example 2
|
||||
Console.WriteLine("Example 2");
|
||||
|
||||
var result=db.UseTran(() =>
|
||||
{
|
||||
|
||||
db.ChangeDatabase("1");//use db1
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
db.Deleteable<Order>().ExecuteCommand();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
throw new Exception("");
|
||||
|
||||
});
|
||||
if (result.IsSuccess == false) {
|
||||
Console.WriteLine("---Roll back");
|
||||
db.ChangeDatabase("1");//use db1
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
}
|
||||
|
||||
// Example 3
|
||||
Console.WriteLine("Example 3");
|
||||
|
||||
var result2 = db.UseTranAsync(async () =>
|
||||
{
|
||||
|
||||
db.ChangeDatabase("1");//use db1
|
||||
await db.Deleteable<Order>().ExecuteCommandAsync();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use db2
|
||||
await db.Deleteable<Order>().ExecuteCommandAsync();
|
||||
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
throw new Exception("");
|
||||
|
||||
});
|
||||
result2.Wait();
|
||||
if (result2.Result.IsSuccess == false)
|
||||
{
|
||||
Console.WriteLine("---Roll back");
|
||||
db.ChangeDatabase("1");//use sqlserver
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
|
||||
db.ChangeDatabase("2");//use TDengine
|
||||
Console.WriteLine(db.CurrentConnectionConfig.DbType);
|
||||
Console.WriteLine(db.Queryable<Order>().Count());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DbContext Example 1
|
||||
/// </summary>
|
||||
public class DbContext
|
||||
{
|
||||
|
||||
public SqlSugarClient Db;
|
||||
public DbContext()
|
||||
{
|
||||
Db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
ConnectionString = Config.ConnectionString,
|
||||
DbType = DbType.TDengine,
|
||||
IsAutoCloseConnection = true,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
AopEvents = new AopEvents()
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
public SimpleClient<Order> OrderDb => new SimpleClient<Order>(Db);
|
||||
public SimpleClient<OrderItem> OrderItemDb => new SimpleClient<OrderItem>(Db);
|
||||
}
|
||||
|
||||
|
||||
public class OrderDal : DbContext<Order>
|
||||
{
|
||||
|
||||
}
|
||||
/// <summary>
|
||||
/// DbContext Example 2
|
||||
/// </summary>
|
||||
/// <typeparam name="T"></typeparam>
|
||||
public class DbContext<T> where T : class, new()
|
||||
{
|
||||
|
||||
public SqlSugarClient Db;
|
||||
public DbContext()
|
||||
{
|
||||
Db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
ConnectionString = Config.ConnectionString,
|
||||
DbType = DbType.TDengine,
|
||||
IsAutoCloseConnection = true,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
AopEvents = new AopEvents()
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
public SimpleClient<T> CurrentDb => new SimpleClient<T>(Db);
|
||||
public virtual T GetById(int id)
|
||||
{
|
||||
return CurrentDb.GetById(id);
|
||||
}
|
||||
public virtual List<T> GetList()
|
||||
{
|
||||
return CurrentDb.GetList();
|
||||
}
|
||||
public virtual bool Delete(int id)
|
||||
{
|
||||
return CurrentDb.DeleteById(id);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -1,346 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Dynamic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo1_Queryable
|
||||
{
|
||||
|
||||
public static void Init()
|
||||
{
|
||||
EasyExamples();
|
||||
QueryConditions();
|
||||
JoinTable();
|
||||
Async();
|
||||
NoEntity();
|
||||
Mapper();
|
||||
SqlFuncTest();
|
||||
Subquery();
|
||||
ReturnType();
|
||||
}
|
||||
|
||||
private static void EasyExamples()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Examples Start ####");
|
||||
var db = GetInstance();
|
||||
var dbTime = db.GetDate();
|
||||
var getAll = db.Queryable<Order>().ToList();
|
||||
var getOrderBy = db.Queryable<Order>().OrderBy(it => it.Name,OrderByType.Desc).ToList();
|
||||
var getOrderBy2 = db.Queryable<Order>().OrderBy(it => it.Id).OrderBy(it => it.Name, OrderByType.Desc).ToList();
|
||||
var getOrderBy3 = db.Queryable<Order>().OrderBy(it =>new { it.Name,it.Id}).ToList();
|
||||
var getRandom = db.Queryable<Order>().OrderBy(it => SqlFunc.GetRandom()).First();
|
||||
var getByPrimaryKey = db.Queryable<Order>().InSingle(2);
|
||||
var getSingleOrDefault = db.Queryable<Order>().Where(it => it.Id == 1).Single();
|
||||
var getFirstOrDefault = db.Queryable<Order>().First();
|
||||
var getByWhere = db.Queryable<Order>().Where(it => it.Id == 1 || it.Name == "a").ToList();
|
||||
var getByWhere2 = db.Queryable<Order>().Where(it => it.Id == DateTime.Now.Year).ToList();
|
||||
var getByFuns = db.Queryable<Order>().Where(it => SqlFunc.IsNullOrEmpty(it.Name)).ToList();
|
||||
var getByFuns2 = db.Queryable<Order>().GroupBy(it => it.Name).Select(it => SqlFunc.AggregateDistinctCount(it.Price)).ToList();
|
||||
var test47 = db.Queryable<Order>().Select(it => new
|
||||
{
|
||||
names = SqlFunc.Subqueryable<Order>().Where(z => z.Id == it.Id).SelectStringJoin(z => z.Name, ",")
|
||||
})
|
||||
.ToList();
|
||||
Console.WriteLine("#### Examples End ####");
|
||||
}
|
||||
|
||||
private static void ReturnType()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### ReturnType Start ####");
|
||||
var db = GetInstance();
|
||||
List<Order> list = db.Queryable<Order>().ToList();
|
||||
|
||||
Order item = db.Queryable<Order>().First(it => it.Id == 1);
|
||||
|
||||
DataTable dataTable = db.Queryable<Order>().Select(it => it.Id).ToDataTable();
|
||||
|
||||
var json = db.Queryable<Order>().ToJson();
|
||||
|
||||
List<int> listInt = db.Queryable<Order>().Select(it => it.Id).ToList();
|
||||
|
||||
var dynamic = db.Queryable<Order>().Select<dynamic>().ToList();
|
||||
|
||||
var viewModel = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId ,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select<ViewOrder>().ToList();
|
||||
|
||||
var newDynamic = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select((o, i, c) => new { orderName = o.Name, cusName=c.Name }).ToList();
|
||||
|
||||
var newClass = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select((o, i, c) => new ViewOrder { Name=o.Name, CustomName=c.Name }).ToList();
|
||||
|
||||
|
||||
var oneClass = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select((o, i, c) => c).ToList();
|
||||
|
||||
var twoClass = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select((o, i, c) => new { o,i}).ToList();
|
||||
|
||||
List<Dictionary<string, object>> ListDic = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, o.CustomId == c.Id
|
||||
))
|
||||
.Select<ExpandoObject>().ToList().Select(it => it.ToDictionary(x => x.Key, x => x.Value)).ToList();
|
||||
Console.WriteLine("#### ReturnType End ####");
|
||||
}
|
||||
|
||||
private static void Subquery()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Subquery Start ####");
|
||||
var db = GetInstance();
|
||||
|
||||
var list = db.Queryable<Order>().Take(10).Select(it => new
|
||||
{
|
||||
customName=SqlFunc.Subqueryable<Custom>().Where("it.CustomId=id").Select(s=>s.Name),
|
||||
customName2 = SqlFunc.Subqueryable<Custom>().Where("it.CustomId = id").Where(s => true).Select(s => s.Name)
|
||||
}).ToList();
|
||||
|
||||
var list2 = db.Queryable<Order>().Where(it => SqlFunc.Subqueryable<OrderItem>().Where(i => i.OrderId == it.Id).Any()).ToList();
|
||||
|
||||
Console.WriteLine("#### Subquery End ####");
|
||||
}
|
||||
|
||||
private static void SqlFuncTest()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### SqlFunc Start ####");
|
||||
var db = GetInstance();
|
||||
var index= db.Queryable<Order>().Select(it => SqlFunc.CharIndex("a", "cccacc")).First();
|
||||
|
||||
Console.WriteLine("#### SqlFunc End ####");
|
||||
}
|
||||
|
||||
private static void Mapper()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Mapper Start ####");
|
||||
var db = GetInstance();
|
||||
//Creater Table
|
||||
db.CodeFirst.InitTables(typeof(Tree));
|
||||
db.DbMaintenance.TruncateTable("Tree");
|
||||
db.Insertable(new Tree() { Id = 1, Name = "root" }).ExecuteCommand();
|
||||
db.Insertable(new Tree() { Id = 11, Name = "child1",ParentId=1 }).ExecuteCommand();
|
||||
db.Insertable(new Tree() { Id = 12, Name = "child2",ParentId=1 }).ExecuteCommand();
|
||||
db.Insertable(new Tree() { Id = 2, Name = "root" }).ExecuteCommand();
|
||||
db.Insertable(new Tree() { Id = 22, Name = "child3", ParentId = 2 }).ExecuteCommand();
|
||||
|
||||
// Same property name mapping,Both entities have parentId
|
||||
var list = db.Queryable<Tree>().Mapper(it => it.Parent, it => it.ParentId).ToList();
|
||||
|
||||
|
||||
//If both entities have parentId, I don't want to associate with parentId.
|
||||
var list1 =db.Queryable<Tree>()
|
||||
//parent=(select * from parent where id=it.parentid)
|
||||
.Mapper(it=>it.Parent,it=>it.ParentId, it=>it.Parent.Id)
|
||||
//Child=(select * from parent where ParentId=it.id)
|
||||
.Mapper(it => it.Child, it => it.Id, it => it.Parent.ParentId)
|
||||
.ToList();
|
||||
//one to one
|
||||
var list2 = db.Queryable<OrderItemInfo>().Mapper(it => it.Order, it => it.OrderId).ToList();
|
||||
|
||||
//one to many
|
||||
var list3 = db.Queryable<Order>().Mapper(it => it.Items, it => it.Items.First().OrderId).ToList();
|
||||
|
||||
//many to many
|
||||
db.CodeFirst.InitTables<A, B, ABMapping>();
|
||||
|
||||
db.Insertable(new A() { Name = "A" }).ExecuteCommand();
|
||||
db.Insertable(new B() { Name = "B" }).ExecuteCommand();
|
||||
db.Insertable(new ABMapping() { AId = 1, BId = 1 }).ExecuteCommand();
|
||||
|
||||
var list4 = db.Queryable<ABMapping>()
|
||||
.Mapper(it => it.A, it => it.AId)
|
||||
.Mapper(it => it.B, it => it.BId).ToList();
|
||||
|
||||
//Manual mode
|
||||
var result = db.Queryable<OrderInfo>().Take(10).Select<ViewOrder>().Mapper((itemModel, cache) =>
|
||||
{
|
||||
var allItems = cache.Get(orderList => {
|
||||
var allIds = orderList.Select(it => it.Id).ToList();
|
||||
return db.Queryable<OrderItem>().Where(it => allIds.Contains(it.OrderId)).ToList();//Execute only once
|
||||
});
|
||||
itemModel.Items = allItems.Where(it => it.OrderId==itemModel.Id).ToList();//Every time it's executed
|
||||
}).ToList();
|
||||
|
||||
Console.WriteLine("#### End Start ####");
|
||||
}
|
||||
|
||||
private static void NoEntity()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### No Entity Start ####");
|
||||
var db = GetInstance();
|
||||
|
||||
var list = db.Queryable<dynamic>().AS("`Order`").Where("id=id", new { id = 1 }).ToList();
|
||||
|
||||
var list2 = db.Queryable<dynamic>("o").AS("`Order`").AddJoinInfo("OrderDetail", "i", "o.id=i.OrderId").Where("id=id", new { id = 1 }).Select("o.*").ToList();
|
||||
Console.WriteLine("#### No Entity End ####");
|
||||
}
|
||||
|
||||
private static void JoinTable()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Join Table Start ####");
|
||||
var db = GetInstance();
|
||||
|
||||
//Simple join
|
||||
var list = db.Queryable<Order, OrderItem, Custom>((o, i, c) => o.Id == i.OrderId&&c.Id == o.CustomId)
|
||||
.Select<ViewOrder>()
|
||||
.ToList();
|
||||
|
||||
//Join table
|
||||
var list2 = db.Queryable<Order, OrderItem, Custom>((o, i, c) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId,
|
||||
JoinType.Left, c.Id == o.CustomId
|
||||
))
|
||||
.Select<ViewOrder>().ToList();
|
||||
|
||||
//Join queryable
|
||||
var query1 = db.Queryable<Order, OrderItem>((o, i) => new JoinQueryInfos(
|
||||
JoinType.Left, o.Id == i.OrderId
|
||||
))
|
||||
.Where(o => o.Name == "jack");
|
||||
|
||||
var query2 = db.Queryable<Custom>();
|
||||
var list3=db.Queryable(query1, query2,JoinType.Left, (p1, p2) => p1.CustomId == p2.Id).Select<ViewOrder>().ToList();
|
||||
|
||||
Console.WriteLine("#### Join Table End ####");
|
||||
}
|
||||
|
||||
private static void QueryConditions()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Query Conditions Start ####");
|
||||
|
||||
SqlSugarClient db = GetInstance();
|
||||
|
||||
/*** By expression***/
|
||||
|
||||
//id=@id
|
||||
var list = db.Queryable<Order>().Where(it => it.Id == 1).ToList();
|
||||
//id=@id or name like '%'+@name+'%'
|
||||
var list2 = db.Queryable<Order>().Where(it => it.Id == 1 || it.Name.Contains("jack")).ToList();
|
||||
|
||||
|
||||
//Create expression
|
||||
var exp = Expressionable.Create<Order>()
|
||||
.And(it => it.Id == 1)
|
||||
.Or(it => it.Name.Contains("jack")).ToExpression();
|
||||
var list3 = db.Queryable<Order>().Where(exp).ToList();
|
||||
|
||||
|
||||
/*** By sql***/
|
||||
|
||||
//id=@id
|
||||
var list4 = db.Queryable<Order>().Where("id=@id", new { id = 1 }).ToList();
|
||||
//id=@id or name like '%'+@name+'%'
|
||||
var list5 = db.Queryable<Order>().Where("id=@id or name like @name ", new { id = 1, name = "%jack%" }).ToList();
|
||||
|
||||
|
||||
|
||||
/*** By dynamic***/
|
||||
|
||||
//id=1
|
||||
var conModels = new List<IConditionalModel>();
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
|
||||
var student = db.Queryable<Order>().Where(conModels).ToList();
|
||||
|
||||
//Complex use case
|
||||
List<IConditionalModel> Order = new List<IConditionalModel>();
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Like, FieldValue = "1" });// id like '%1%'
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNullOrEmpty });
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.In, FieldValue = "1,2,3" });
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NotIn, FieldValue = "1,2,3" });
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.NoEqual, FieldValue = "1,2,3" });
|
||||
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.IsNot, FieldValue = null });// id is not null
|
||||
|
||||
conModels.Add(new ConditionalCollections()
|
||||
{
|
||||
ConditionalList = new List<KeyValuePair<WhereType, SqlSugar.ConditionalModel>>()// (id=1 or id=2 and id=1)
|
||||
{
|
||||
//new KeyValuePair<WhereType, ConditionalModel>( WhereType.And ,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" }),
|
||||
new KeyValuePair<WhereType, ConditionalModel> (WhereType.Or,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" }),
|
||||
new KeyValuePair<WhereType, ConditionalModel> ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" })
|
||||
}
|
||||
});
|
||||
var list6 = db.Queryable<Order>().Where(conModels).ToList();
|
||||
|
||||
/*** Conditional builder ***/
|
||||
|
||||
// use whereif
|
||||
string name = "";
|
||||
int id = 1;
|
||||
var query = db.Queryable<Order>()
|
||||
.WhereIF(!string.IsNullOrEmpty(name), it => it.Name.Contains(name))
|
||||
.WhereIF(id > 0, it => it.Id == id).ToList();
|
||||
//clone new Queryable
|
||||
var query2 = db.Queryable<Order>().Where(it => it.Id == 1);
|
||||
var list7 = query2.Clone().Where(it => it.Name == "jack").ToList();//id=1 and name = jack
|
||||
var list8 = query2.Clone().Where(it => it.Name == "tom").ToList();//id=1 and name = tom
|
||||
|
||||
Console.WriteLine("#### Condition Screening End ####");
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
private static void Async()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Async Start ####");
|
||||
|
||||
SqlSugarClient db = GetInstance();
|
||||
var task1 = db.Queryable<Order>().FirstAsync();
|
||||
task1.Wait();
|
||||
var task2 = db.Queryable<Order>().Where(it => it.Id == 1).ToListAsync();
|
||||
|
||||
|
||||
task2.Wait();
|
||||
|
||||
Console.WriteLine("#### Async End ####");
|
||||
}
|
||||
|
||||
private static SqlSugarClient GetInstance()
|
||||
{
|
||||
return new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = SqlSugar.DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
@ -1,114 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo2_Updateable
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Updateable Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
/*** 1.entity or List ***/
|
||||
|
||||
var updateObj = new Order() { Id = 1, Name = "order1" };
|
||||
var updateObjs = new List<Order> {
|
||||
new Order() { Id = 11, Name = "order11" },
|
||||
new Order() { Id = 12, Name = "order12" }
|
||||
};
|
||||
|
||||
//update all columns by primary key
|
||||
var result = db.Updateable(updateObj).ExecuteCommand();//update single
|
||||
var result2 = db.Updateable(updateObjs).ExecuteCommand();//update List<Class>
|
||||
|
||||
//Ignore Name and Price
|
||||
var result3 = db.Updateable(updateObj).IgnoreColumns(it => new { it.CreateTime, it.Price }).ExecuteCommand();
|
||||
|
||||
//only update Name and CreateTime
|
||||
var result4 = db.Updateable(updateObj).UpdateColumns(it => new { it.Name, it.CreateTime }).ExecuteCommand();
|
||||
|
||||
//If there is no primary key
|
||||
var result5 = db.Updateable(updateObj).WhereColumns(it => new { it.Id }).ExecuteCommand();//update single by id
|
||||
var result6 = db.Updateable(updateObjs).WhereColumns(it => new { it.Id }).ExecuteCommand();//update List<Class> by id
|
||||
|
||||
|
||||
|
||||
|
||||
/*** 2.by expression ***/
|
||||
|
||||
//update name,createtime
|
||||
var result7 = db.Updateable<Order>(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand();
|
||||
var result71 = db.Updateable<Order>().SetColumns(it => new Order() { Name = "a", CreateTime = DateTime.Now }).Where(it => it.Id == 11).ExecuteCommand();
|
||||
//only update name
|
||||
var result8 = db.Updateable<Order>(it => it.Name == "Name" + "1").Where(it => it.Id == 1).ExecuteCommand();
|
||||
var result81 = db.Updateable<Order>().SetColumns(it => it.Name == "Name" + "1").Where(it => it.Id == 1).ExecuteCommand();
|
||||
//
|
||||
var result61 = db.Updateable<Order>()
|
||||
.InnerJoin<Custom>((x, y) => x.CustomId == y.Id)
|
||||
.SetColumns((x, y) => new Order() { Name = y.Name, Price = y.Id })
|
||||
.Where((x, y) => x.Id == 1)
|
||||
.ExecuteCommand();
|
||||
|
||||
db.Updateable<Order>().SetColumns(it => it.Name == "a")
|
||||
.Where(it => SqlFunc.Subqueryable<Order>().Where(s=>s.Id==it.Id).Any())
|
||||
.ExecuteCommand();
|
||||
|
||||
|
||||
/*** 3.by Dictionary ***/
|
||||
var dt = new Dictionary<string, object>();
|
||||
dt.Add("id", 1);
|
||||
dt.Add("name", "abc");
|
||||
dt.Add("createTime", DateTime.Now);
|
||||
var dtList = new List<Dictionary<string, object>>();
|
||||
dtList.Add(dt);
|
||||
|
||||
var t66 = db.Updateable(dt).AS("`Order`").WhereColumns("id").ExecuteCommand();
|
||||
var t666 = db.Updateable(dtList).AS("`Order`").WhereColumns("id").ExecuteCommand();
|
||||
|
||||
|
||||
|
||||
/*** 4.Other instructions ***/
|
||||
|
||||
var caseValue = "1";
|
||||
//Do not update NULL columns
|
||||
db.Updateable(updateObj).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();
|
||||
|
||||
//if 1 update name else if 2 update name,createtime
|
||||
db.Updateable(updateObj)
|
||||
.UpdateColumnsIF(caseValue == "1", it => new { it.Name })
|
||||
.UpdateColumnsIF(caseValue == "2", it => new { it.Name, it.CreateTime })
|
||||
.ExecuteCommand();
|
||||
//Use Lock
|
||||
db.Updateable(updateObj).With(SqlWith.UpdLock).ExecuteCommand();
|
||||
|
||||
//Where Sql
|
||||
//db.Updateable(updateObj).Where("id=@x", new { x = "1" }).ExecuteCommand();
|
||||
|
||||
Console.WriteLine("#### Updateable End ####");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
@ -1,56 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo3_Insertable
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Insertable Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var insertObj = new Order() { Id = 1, Name = "order1",Price=0 };
|
||||
var updateObjs = new List<Order> {
|
||||
new Order() { Id = 11, Name = "order11", Price=0 },
|
||||
new Order() { Id = 12, Name = "order12" , Price=0}
|
||||
};
|
||||
|
||||
//Ignore CreateTime
|
||||
db.Insertable(insertObj).IgnoreColumns(it => new { it.CreateTime }).ExecuteReturnIdentity();//get identity
|
||||
db.Insertable(insertObj).IgnoreColumns("CreateTime").ExecuteReturnIdentity();
|
||||
|
||||
//Only insert Name and Price
|
||||
db.Insertable(insertObj).InsertColumns(it => new { it.Name, it.Price }).ExecuteReturnIdentity();
|
||||
db.Insertable(insertObj).InsertColumns("Name", "Price").ExecuteReturnIdentity();
|
||||
|
||||
//ignore null columns
|
||||
db.Insertable(updateObjs).ExecuteCommand();//get change row count
|
||||
|
||||
//Use Lock
|
||||
db.Insertable(insertObj).With(SqlWith.UpdLock).ExecuteCommand();
|
||||
|
||||
Console.WriteLine("#### Insertable End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo4_Deleteable
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Deleteable Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
//by entity
|
||||
db.Deleteable<Order>().Where(new Order() { Id = 1111 }).ExecuteCommand();
|
||||
|
||||
//by primary key
|
||||
db.Deleteable<Order>().In(1111).ExecuteCommand();
|
||||
|
||||
//by primary key array
|
||||
db.Deleteable<Order>().In(new int[] { 1111, 2222 }).ExecuteCommand();
|
||||
|
||||
//by expression
|
||||
db.Deleteable<Order>().Where(it => it.Id == 11111).ExecuteCommand();
|
||||
|
||||
Console.WriteLine("#### Deleteable End ####");
|
||||
|
||||
}
|
||||
}
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo5_SqlQueryable
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### SqlQueryable Start ####");
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true
|
||||
});
|
||||
|
||||
int total = 0;
|
||||
var list = db.SqlQueryable<Order>("select * from `Order`").ToPageList(1, 2, ref total);
|
||||
|
||||
|
||||
//by expression
|
||||
var list2 = db.SqlQueryable<Order>("select * from `Order`").Where(it => it.Id == 1).ToPageList(1, 2);
|
||||
//by sql
|
||||
var list3 = db.SqlQueryable<Order>("select * from `Order`").Where("id=@id", new { id = 1 }).ToPageList(1, 2);
|
||||
|
||||
Console.WriteLine("#### SqlQueryable End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,52 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo6_Queue
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Queue Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
db.Insertable<Order>(new Order() { Name = "a" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "b" }).AddQueue();
|
||||
db.SaveQueues();
|
||||
|
||||
|
||||
db.Insertable<Order>(new Order() { Name = "a" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "b" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "c" }).AddQueue();
|
||||
db.Insertable<Order>(new Order() { Name = "d" }).AddQueue();
|
||||
var ar = db.SaveQueuesAsync();
|
||||
ar.Wait();
|
||||
|
||||
db.Queryable<Order>().AddQueue();
|
||||
db.Queryable<Order>().AddQueue();
|
||||
db.AddQueue("select * from `order` where id=@id", new { id = 10000 });
|
||||
var result2 = db.SaveQueues<Order, Order, Order>();
|
||||
|
||||
Console.WriteLine("#### Queue End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,57 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo7_Ado
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Ado Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
//sql
|
||||
var dt = db.Ado.GetDataTable("select * from `Order` where @id>0 or name=@name", new List<SugarParameter>(){
|
||||
new SugarParameter("@id",1),
|
||||
new SugarParameter("@name","2")
|
||||
});
|
||||
|
||||
//sql
|
||||
var dt2 = db.Ado.GetDataTable("select * from `Order` where @id>0 or name=@name", new { id = 1, name = "2" });
|
||||
|
||||
//Stored Procedure
|
||||
//var dt3 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", new { name = "张三", age = 0 });
|
||||
//var nameP = new SugarParameter("@name", "张三");
|
||||
//var ageP = new SugarParameter("@age", null, true);//isOutput=true
|
||||
//var dt4 = db.Ado.UseStoredProcedure().GetDataTable("sp_school", nameP, ageP);
|
||||
|
||||
|
||||
|
||||
//There are many methods to under db.ado
|
||||
var list= db.Ado.SqlQuery<Order>("select * from `Order` ");
|
||||
var intValue=db.Ado.SqlQuerySingle<int>("select 1");
|
||||
db.Ado.ExecuteCommand("delete from `Order` where id>1000");
|
||||
//db.Ado.xxx
|
||||
Console.WriteLine("#### Ado End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo8_Saveable
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Saveable Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
//insert or update
|
||||
db.Saveable<Order>(new Order() { Id=1, Name="jack" }).ExecuteReturnEntity();
|
||||
|
||||
|
||||
//insert or update
|
||||
db.Saveable<Order>(new Order() { Id = 1000, Name = "jack", CreateTime=DateTime.Now })
|
||||
.InsertColumns(it => new { it.Name,it.CreateTime, it.Price})//if insert into name,CreateTime,Price
|
||||
.UpdateColumns(it => new { it.Name, it.CreateTime })//if update set name CreateTime
|
||||
.ExecuteReturnEntity();
|
||||
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Saveable End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class Demo9_EntityMain
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### EntityMain Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
var entityInfo = db.EntityMaintenance.GetEntityInfo<Order>();
|
||||
foreach (var column in entityInfo.Columns)
|
||||
{
|
||||
Console.WriteLine(column.DbColumnName);
|
||||
}
|
||||
|
||||
var dbColumnsName = db.EntityMaintenance.GetDbColumnName<EntityMapper>("Name");
|
||||
|
||||
var dbTableName = db.EntityMaintenance.GetTableName<EntityMapper>();
|
||||
|
||||
//more https://github.com/sunkaixuan/SqlSugar/wiki/9.EntityMain
|
||||
Console.WriteLine("#### EntityMain End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,42 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class DemoA_DbMain
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### DbMain Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
var tables = db.DbMaintenance.GetTableInfoList();
|
||||
foreach (var table in tables)
|
||||
{
|
||||
Console.WriteLine(table.Description);
|
||||
}
|
||||
//more https://github.com/sunkaixuan/SqlSugar/wiki/a.DbMain
|
||||
Console.WriteLine("#### DbMain End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,68 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class DemoB_Aop
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Aop Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true
|
||||
});
|
||||
db.Aop.OnLogExecuted = (sql, pars) => //SQL executed event
|
||||
{
|
||||
Console.WriteLine("OnLogExecuted"+sql);
|
||||
};
|
||||
db.Aop.OnLogExecuting = (sql, pars) => //SQL executing event (pre-execution)
|
||||
{
|
||||
Console.WriteLine("OnLogExecuting" + sql);
|
||||
};
|
||||
db.Aop.OnError = (exp) =>//SQL execution error event
|
||||
{
|
||||
//exp.sql
|
||||
};
|
||||
db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL executing event (pre-execution,SQL script can be modified)
|
||||
{
|
||||
return new KeyValuePair<string, SugarParameter[]>(sql, pars);
|
||||
};
|
||||
db.Aop.OnDiffLogEvent = it =>//Get data changes
|
||||
{
|
||||
var editBeforeData = it.BeforeData;
|
||||
var editAfterData = it.AfterData;
|
||||
var sql = it.Sql;
|
||||
var parameter = it.Parameters;
|
||||
var businessData = it.BusinessData;
|
||||
var time = it.Time;
|
||||
var diffType = it.DiffType;//enum insert 、update and delete
|
||||
Console.WriteLine(businessData);
|
||||
Console.WriteLine(editBeforeData[0].Columns[1].Value);
|
||||
Console.WriteLine("to");
|
||||
Console.WriteLine(editAfterData[0].Columns[1].Value);
|
||||
//Write logic
|
||||
};
|
||||
|
||||
|
||||
db.Queryable<Order>().ToList();
|
||||
db.Queryable<OrderItem>().ToList();
|
||||
|
||||
//OnDiffLogEvent
|
||||
var data = db.Queryable<Order>().First();
|
||||
data.Name = "changeName";
|
||||
db.Updateable(data).EnableDiffLogEvent("--update Order--").ExecuteCommand();
|
||||
|
||||
Console.WriteLine("#### Aop End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,75 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class DemoD_DbFirst
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("#### DbFirst Start ####");
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true
|
||||
});
|
||||
|
||||
db.DbFirst.CreateClassFile("c:\\Demo\\1", "Models");
|
||||
|
||||
|
||||
db.DbFirst.Where("Student").CreateClassFile("c:\\Demo\\2", "Models");
|
||||
|
||||
|
||||
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\3", "Models");
|
||||
|
||||
|
||||
db.DbFirst.Where(it => it.ToLower().StartsWith("view")).CreateClassFile("c:\\Demo\\4", "Models");
|
||||
|
||||
|
||||
db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\5", "Models");
|
||||
|
||||
|
||||
db.DbFirst.IsCreateDefaultValue().CreateClassFile("c:\\Demo\\6", "Demo.Models");
|
||||
|
||||
|
||||
db.DbFirst. SettingClassTemplate(old => { return old;})
|
||||
.SettingNamespaceTemplate(old =>{ return old;})
|
||||
.SettingPropertyDescriptionTemplate(old =>
|
||||
{
|
||||
return @" /// <summary>
|
||||
/// Desc_New:{PropertyDescription}
|
||||
/// Default_New:{DefaultValue}
|
||||
/// Nullable_New:{IsNullable}
|
||||
/// </summary>";
|
||||
})
|
||||
.SettingPropertyTemplate(old =>{return old;})
|
||||
.SettingConstructorTemplate(old =>{return old; })
|
||||
.CreateClassFile("c:\\Demo\\7");
|
||||
|
||||
|
||||
|
||||
foreach (var item in db.DbMaintenance.GetTableInfoList())
|
||||
{
|
||||
string entityName = item.Name.ToUpper();/*Format class name*/
|
||||
db.MappingTables.Add(entityName , item.Name);
|
||||
foreach (var col in db.DbMaintenance.GetColumnInfosByTableName(item.Name))
|
||||
{
|
||||
db.MappingColumns.Add(col.DbColumnName.ToUpper() /*Format class property name*/, col.DbColumnName, entityName);
|
||||
}
|
||||
}
|
||||
db.DbFirst.IsCreateAttribute().CreateClassFile("c:\\Demo\\8", "Models");
|
||||
|
||||
|
||||
//Use Razor Template
|
||||
//db.DbFirst.UseRazorAnalysis(RazorFirst.DefaultRazorClassTemplate).CreateClassFile("");
|
||||
|
||||
Console.WriteLine("#### DbFirst End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,63 +0,0 @@
|
||||
using Newtonsoft.Json.Linq;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class DemoE_CodeFirst
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### CodeFirst Start ####");
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString3,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true
|
||||
});
|
||||
db.Aop.OnLogExecuting = (s, p) => Console.WriteLine(UtilMethods.GetNativeSql(s, p));
|
||||
db.DbMaintenance.CreateDatabase();
|
||||
db.CodeFirst.InitTables(typeof(CodeFirstTable1));//Create CodeFirstTable1
|
||||
db.Insertable(new CodeFirstTable1() { Name = "a", Text="a" }).ExecuteCommand();
|
||||
db.CodeFirst.InitTables<CharTest>();
|
||||
db.Insertable(new CharTest() { xx = Guid.NewGuid().ToString() }).ExecuteCommand();
|
||||
var list=db.Queryable<CharTest>().ToList();
|
||||
db.CodeFirst.InitTables<Charafafa2>();
|
||||
db.Insertable(new Charafafa2() { TimeSpanTimeSpan = TimeSpan.FromSeconds(1) }).ExecuteCommand();
|
||||
var list2=db.Queryable<Charafafa2>().ToList();
|
||||
db.CodeFirst.InitTables<Codeafadfa>();
|
||||
db.Insertable(new Codeafadfa() { Array = JArray.FromObject(new string[] { "a" }) }).ExecuteCommand();
|
||||
Console.WriteLine("#### CodeFirst end ####");
|
||||
}
|
||||
}
|
||||
public class Codeafadfa
|
||||
{
|
||||
[SugarColumn(ColumnDataType ="varchar(500)" )]
|
||||
public object Array { get; set; }
|
||||
}
|
||||
public class Charafafa2
|
||||
{
|
||||
public TimeSpan TimeSpanTimeSpan { get; set; }
|
||||
}
|
||||
public class CharTest
|
||||
{
|
||||
[SugarColumn(ColumnDataType ="char(36)")]
|
||||
public string xx { get; set; }
|
||||
}
|
||||
|
||||
public class CodeFirstTable1
|
||||
{
|
||||
[SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
|
||||
public int Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
[SugarColumn(ColumnDataType = "Nvarchar(255)")]//custom
|
||||
public string Text { get; set; }
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime CreateTime { get; set; }
|
||||
}
|
||||
}
|
@ -1,46 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class DemoF_Utilities
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Utilities Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
List<int> ids = Enumerable.Range(1, 100).ToList();
|
||||
db.Utilities.PageEach(ids, 10, list =>
|
||||
{
|
||||
Console.WriteLine(string.Join("," ,list));
|
||||
});
|
||||
|
||||
var list2= db.Utilities.DataTableToList<Order>(db.Ado.GetDataTable("select * from `Order`"));
|
||||
|
||||
//more https://github.com/sunkaixuan/SqlSugar/wiki/f.Utilities
|
||||
Console.WriteLine("#### Utilities End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,36 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class DemoG_SimpleClient
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### SimpleClient Start ####");
|
||||
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = DbType.TDengine,
|
||||
ConnectionString = Config.ConnectionString,
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Console.WriteLine("#### SimpleClient End ####");
|
||||
}
|
||||
}
|
||||
}
|
@ -1,118 +0,0 @@
|
||||
using OrmTest;
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace TDengineTest.Demo
|
||||
{
|
||||
public class DemoH_Tree
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Test_ToParentList();
|
||||
Test_ToParentListWhere();
|
||||
Task.Run(Test_ToParentListAsync).Wait();
|
||||
Task.Run(Test_ToParentListWhereAsync).Wait();
|
||||
}
|
||||
|
||||
private static void Test_ToParentList()
|
||||
{
|
||||
var db = GetInstance();
|
||||
var data = db.Queryable<CustomerAddressTemplateDetail>().ToParentList(x => x.ParentCode, 2);
|
||||
var data2 = db.Queryable<District>().ToParentList(x => x.ParentId, 110101004004);
|
||||
}
|
||||
|
||||
private static void Test_ToParentListWhere()
|
||||
{
|
||||
var db = GetInstance();
|
||||
var data = db.Queryable<CustomerAddressTemplateDetail>().ToParentList(x => x.ParentCode, 2, x => x.TemplateId == 1611933284013932544);
|
||||
var data2 = db.Queryable<District>().ToParentList(x => x.ParentId, 110101004004,x=>x.DeletedAt==0);
|
||||
}
|
||||
private static async Task Test_ToParentListAsync()
|
||||
{
|
||||
var db = GetInstance();
|
||||
var data = await db.Queryable<CustomerAddressTemplateDetail>().ToParentListAsync(x => x.ParentCode, 2);
|
||||
var data2 = await db.Queryable<District>().ToParentListAsync(x => x.ParentId, 110101004004);
|
||||
}
|
||||
|
||||
private static async Task Test_ToParentListWhereAsync()
|
||||
{
|
||||
var db = GetInstance();
|
||||
var data = await db.Queryable<CustomerAddressTemplateDetail>().ToParentListAsync(x => x.ParentCode, 2, x => x.TemplateId == 1611933284013932544);
|
||||
var data2 = await db.Queryable<District>().ToParentListAsync(x => x.ParentId, 110101004004, x => x.DeletedAt == 0);
|
||||
}
|
||||
|
||||
private static SqlSugarClient GetInstance()
|
||||
{
|
||||
return new SqlSugarClient(new ConnectionConfig()
|
||||
{
|
||||
DbType = SqlSugar.DbType.TDengine,
|
||||
ConnectionString = "Data Source=192.168.95.11;port=33306;Database=cube;AllowLoadLocalInfile=true;User ID=root;Password=dljs2022;allowPublicKeyRetrieval=true;pooling=true;CharSet=utf8;sslmode=none;AllowUserVariables=true;",
|
||||
InitKeyType = InitKeyType.Attribute,
|
||||
IsAutoCloseConnection = true,
|
||||
AopEvents = new AopEvents
|
||||
{
|
||||
OnLogExecuting = (sql, p) =>
|
||||
{
|
||||
Console.WriteLine(sql);
|
||||
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[SugarTable("customer_address_template_detail", TableDescription = "客户地址模板详情")]
|
||||
[SugarIndex("idx_code", nameof(Code), OrderByType.Asc)]
|
||||
public class CustomerAddressTemplateDetail
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true)]
|
||||
public long Id { get; set; }
|
||||
/// <summary>
|
||||
/// 模板id
|
||||
/// </summary>
|
||||
[SugarColumn(ColumnDescription = "模板id")]
|
||||
public long TemplateId { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDescription = "地址", Length = 128,IsTreeKey = true)]
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
[SugarColumn(ColumnDescription = "上级地址", Length = 128)]
|
||||
public string ParentCode { get; set; } = string.Empty;
|
||||
|
||||
[SugarColumn(ColumnDescription = "名称", Length = 256)]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
[SugarColumn(ColumnDescription = "级别")]
|
||||
public int Level { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDescription = "得力末级地址")]
|
||||
public long DistrictId { get; set; }
|
||||
|
||||
|
||||
}
|
||||
[SugarTable("district", TableDescription = "省市区街道村5级信息(https://github.com/adyliu/china_area)")]
|
||||
[SugarIndex("idx_parentid_level", nameof(ParentId), OrderByType.Asc, nameof(Level), OrderByType.Asc)]
|
||||
public class District
|
||||
{
|
||||
[SugarColumn(IsPrimaryKey = true)]
|
||||
public long Id { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDescription = "上级Id")]
|
||||
public long ParentId { get; set; }
|
||||
|
||||
[SugarColumn(ColumnDescription = "名称", Length = 128)]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
[SugarColumn(ColumnDescription = "级别")]
|
||||
public int Level { get; set; }
|
||||
|
||||
public long DeletedAt { get; set; }
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -1,77 +0,0 @@
|
||||
using SqlSugar;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace OrmTest
|
||||
{
|
||||
public class DemoC_GobalFilter
|
||||
{
|
||||
public static void Init()
|
||||
{
|
||||
Console.WriteLine("");
|
||||
Console.WriteLine("#### Filter Start ####");
|
||||
var db = GetInstance();
|
||||
|
||||
|
||||
var sql = db.Queryable<Order>().ToSql();
|
||||
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE isDelete=0
|
||||
Console.WriteLine(sql);
|
||||
|
||||
|
||||
var sql2 = db.Queryable<Order,OrderItem>((main,ot)=> main.Id==ot.OrderId).ToSql();
|
||||
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` main ,[OrderDetail] ot WHERE ( [main].[Id] = [ot].[OrderId] ) AND main.isDelete=0
|
||||
Console.WriteLine(sql2);
|
||||
|
||||
|
||||
var sql3 = db.Queryable<Order>().Filter("Myfilter").ToSql();// Myfilter+Gobal
|
||||
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE Name='jack' AND isDelete=0
|
||||
Console.WriteLine(sql3);
|
||||
|
||||
var sql4 = db.Queryable<Order>().Filter("Myfilter",isDisabledGobalFilter:true).ToSql();//only Myfilter
|
||||
//SELECT [Id],[Name],[Price],[CreateTime] FROM `order` WHERE Name='jack'
|
||||
Console.WriteLine(sql4);
|
||||
Console.WriteLine("#### Filter End ####");
|
||||
}
|
||||
|
||||
|
||||
public static SqlSugarClient GetInstance()
|
||||
{
|
||||
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { DbType = DbType.TDengine, ConnectionString = Config.ConnectionString, IsAutoCloseConnection = true });
|
||||
|
||||
//single table query gobal filter
|
||||
db.QueryFilter.Add(new SqlFilterItem()
|
||||
{
|
||||
FilterValue = filterDb =>
|
||||
{
|
||||
//Writable logic
|
||||
return new SqlFilterResult() { Sql = " isDelete=0" };//Global string perform best
|
||||
}
|
||||
});
|
||||
|
||||
//Multi-table query gobal filter
|
||||
db.QueryFilter.Add(new SqlFilterItem()
|
||||
{
|
||||
FilterValue = filterDb =>
|
||||
{
|
||||
//Writable logic
|
||||
return new SqlFilterResult() { Sql = " main.isDelete=0" };
|
||||
},
|
||||
IsJoinQuery=true
|
||||
});
|
||||
|
||||
//Specific filters
|
||||
db.QueryFilter.Add(new SqlFilterItem()
|
||||
{
|
||||
FilterName= "Myfilter",
|
||||
FilterValue = filterDb =>
|
||||
{
|
||||
//Writable logic
|
||||
return new SqlFilterResult() { Sql = "Name='jack'" };
|
||||
}
|
||||
});
|
||||
return db;
|
||||
}
|
||||
}
|
||||
}
|
@ -9,28 +9,6 @@ namespace OrmTest
|
||||
{
|
||||
//Demo
|
||||
Demo0_SqlSugarClient.Init();
|
||||
Demo1_Queryable.Init();
|
||||
Demo2_Updateable.Init();
|
||||
Demo3_Insertable.Init();
|
||||
Demo4_Deleteable.Init();
|
||||
Demo5_SqlQueryable.Init();
|
||||
Demo6_Queue.Init();
|
||||
Demo7_Ado.Init();
|
||||
Demo8_Saveable.Init();
|
||||
Demo9_EntityMain.Init();
|
||||
DemoA_DbMain.Init();
|
||||
DemoB_Aop.Init();
|
||||
DemoC_GobalFilter.Init();
|
||||
DemoD_DbFirst.Init(); ;
|
||||
DemoE_CodeFirst.Init();
|
||||
DemoF_Utilities.Init();
|
||||
DemoG_SimpleClient.Init();
|
||||
|
||||
//Unit test
|
||||
//NewUnitTest.Init();
|
||||
|
||||
//Rest Data
|
||||
NewUnitTest.RestData();
|
||||
|
||||
Console.WriteLine("all successfully.");
|
||||
Console.ReadKey();
|
||||
|
Loading…
Reference in New Issue
Block a user