Add GBase

This commit is contained in:
sunkaixuan 2022-08-23 00:30:09 +08:00
parent 76fd8b07a8
commit 3f790e0c1d
57 changed files with 4556 additions and 5 deletions

View File

@ -0,0 +1,10 @@
[*.cs]
# CS8618: 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
dotnet_diagnostic.CS8618.severity = none
# CS8625: 无法将 null 字面量转换为非 null 的引用类型。
dotnet_diagnostic.CS8625.severity = none
# CS8604: 引用类型参数可能为 null。
dotnet_diagnostic.CS8604.severity = none

View File

@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
/// <summary>
/// Setting up the database name does not require you to create the database
/// 设置好数据库名不需要你去手动建库
/// </summary>
public class Config
{
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString = "Driver={GBase ODBC DRIVER (64-Bit)};Host=localhost;Service=19088;Server=gbase01;Database=testdb;Protocol=onsoctcp;Uid=gbasedbt;Pwd=GBase123;Db_locale=zh_CN.utf8;Client_locale=zh_CN.utf8";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString2 = "Driver={GBase ODBC DRIVER (64-Bit)};Host=localhost;Service=19088;Server=gbase01;Database=testdb2;Protocol=onsoctcp;Uid=gbasedbt;Pwd=GBase123;Db_locale=zh_CN.utf8;Client_locale=zh_CN.utf8";
/// <summary>
/// Account have permission to create database
/// 用有建库权限的数据库账号
/// </summary>
public static string ConnectionString3 = "Driver={GBase ODBC DRIVER (64-Bit)};Host=localhost;Service=19088;Server=gbase01;Database=testdb3;Protocol=onsoctcp;Uid=gbasedbt;Pwd=GBase123;Db_locale=zh_CN.utf8;Client_locale=zh_CN.utf8";
}
}

View File

@ -0,0 +1,422 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
namespace OrmTest
{
public class Demo0_SqlSugarClient
{
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()
{
ConnectionString = Config.ConnectionString,//Master Connection
DbType = DbType.GBase,
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.GBase,
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)));
}
}
});
//If no exist create datebase
db.DbMaintenance.CreateDatabase();
//Use db query
var dt = db.Ado.GetDataTable("select 1");
//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();
//Insert data
db.Insertable(new OrderItem() { OrderId = id, Price = 0, CreateTime=DateTime.Now }).ExecuteCommand();
Console.WriteLine("#### SqlSugarClient End ####");
}
private static void DbContext()
{
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", FieldValueConvertFunc=it=>Convert.ToInt32(it) });//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.GBase,
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 ####");
}
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.GBase,
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.GBase, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
new ConnectionConfig(){ ConfigId="2", DbType=DbType.GBase, 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 mysql
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.GBase,
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.GBase,
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);
}
}
}

View File

@ -0,0 +1,342 @@
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();
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.Contains("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)
.Where(it=>it.A.Id==1).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" , FieldValueConvertFunc=it=>Convert.ToInt32(it) });//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", FieldValueConvertFunc = it => Convert.ToInt32(it) });//id=1
//conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Like, FieldValue = "1", FieldValueConvertFunc = it => Convert.ToInt32(it) });// 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" , FieldValueConvertFunc = it => Convert.ToInt32(it) }),
new KeyValuePair<WhereType, ConditionalModel> ( WhereType.And,new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "2" ,FieldValueConvertFunc = it => Convert.ToInt32(it)})
}
});
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.GBase,
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)));
}
}
});
}
}
}

View File

@ -0,0 +1,107 @@
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.GBase,
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").Where(it => it.Id == 1).ExecuteCommand();
var result81 = db.Updateable<Order>().SetColumns(it => it.Name == "Name" ).Where(it => it.Id == 1).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 ####");
}
}
}

View File

@ -0,0 +1,56 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,48 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,37 @@

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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,52 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,57 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,48 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,46 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,42 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,68 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,75 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,40 @@
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.GBase,
ConnectionString = Config.ConnectionString3,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true
});
db.DbMaintenance.CreateDatabase();
db.CodeFirst.InitTables(typeof(CodeFirstTable1));//Create CodeFirstTable1
db.Insertable(new CodeFirstTable1() { Name = "a", Text="a" }).ExecuteCommand();
var list = db.Queryable<CodeFirstTable1>().ToList();
Console.WriteLine("#### CodeFirst end ####");
}
}
public class CodeFirstTable1
{
[SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
public int Id { get; set; }
public string Name { get; set; }
[SugarColumn(ColumnDataType = "varchar(255)")]//custom
public string Text { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime CreateTime { get; set; }
}
}

View File

@ -0,0 +1,46 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,36 @@
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.GBase,
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 ####");
}
}
}

View File

@ -0,0 +1,77 @@
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.GBase, 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;
}
}
}

View File

@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@ -9,4 +9,9 @@
<PackageReference Include="System.Data.Odbc" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SqlSugar.GBaseCore\SqlSugar.GBaseCore.csproj" />
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
namespace OrmTest
{
[Table("MyAttributeTable")]
//[SugarTable("CustomAttributeTable")]
public class AttributeTable
{
[Key]
//[SugarColumn(IsPrimaryKey =true)]
public string Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,7 @@
namespace OrmTest
{
public class CarType
{
public bool State { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public class Custom
{
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
namespace OrmTest
{
[SugarTable("MyEntityMapper")]
public class EntityMapper
{
[SugarColumn(ColumnName ="MyName")]
public string Name { get; set; }
}
}

View File

@ -0,0 +1,54 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
[SugarTable("OrderDetail")]
public class OrderItemInfo
{
[SqlSugar.SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int ItemId { get; set; }
public int OrderId { get; set; }
public decimal? Price { get; set; }
[SqlSugar.SugarColumn(IsNullable = true)]
public DateTime? CreateTime { get; set; }
[SugarColumn(IsIgnore = true)]
public Order Order { get; set; }
}
[SugarTable("Order")]
public class OrderInfo
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
[SugarColumn(IsIgnore = true)]
public List<OrderItem> Items { get; set; }
}
public class ABMapping
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int AId { get; set; }
public int BId { get; set; }
[SugarColumn(IsIgnore = true)]
public A A { get; set; }
[SugarColumn(IsIgnore = true)]
public B B { get; set; }
}
public class A
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
}
public class B
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
namespace OrmTest
{
[Table("CustomAttributeTable")]
//[SugarTable("CustomAttributeTable")]
public class MyCustomAttributeTable
{
[Key]
//[SugarColumn(IsPrimaryKey =true)]
public string Id { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,24 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrmTest
{
public class Order
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
[SugarColumn(IsNullable = true)]
public DateTime CreateTime { get; set; }
[SugarColumn(IsNullable =true)]
public int CustomId { get; set; }
[SugarColumn(IsIgnore = true)]
public List<OrderItem> Items { get; set; }
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OrmTest
{
[SqlSugar.SugarTable("OrderDetail")]
public class OrderItem
{
[SqlSugar.SugarColumn(IsPrimaryKey =true, IsIdentity =true)]
public int ItemId { get; set; }
public int OrderId { get; set; }
public decimal? Price { get; set; }
[SqlSugar.SugarColumn(IsNullable = true)]
public DateTime? CreateTime { get; set; }
}
}

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public class TestTree
{
[SqlSugar.SugarColumn(ColumnDataType = "hierarchyid")]
public string TreeId { get; set; }
[SqlSugar.SugarColumn(ColumnDataType = "Geography")]
public string GId { get; set; }
public string Name { get; set; }
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public class Tree
{
[SqlSugar.SugarColumn(IsPrimaryKey =true)]
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
[SqlSugar.SugarColumn(IsIgnore = true)]
public Tree Parent { get; set; }
[SqlSugar.SugarColumn(IsIgnore = true)]
public List<Tree> Child { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public class ViewOrder:Order
{
public string CustomName { get; set; }
}
}

View File

@ -1,4 +1,5 @@
using System;
using OrmTest;
using System;
namespace GbaseTest
{
@ -6,8 +7,7 @@ namespace GbaseTest
{
static void Main(string[] args)
{
var odbc= new System.Data.Odbc.OdbcConnection(@"Driver={GBase ODBC 8.3 DRIVER};Server=localhost;port=19088;Database=;Protocol=onsoctcp;Uid=gbasedbt;Pwd=GBase123;");
odbc.Open();
Demo0_SqlSugarClient.Init();
Console.WriteLine("Hello World!");
}
}

View File

@ -11,6 +11,10 @@
<None Remove="UnitTest\models\**" />
</ItemGroup>
<ItemGroup>
<None Include="..\.editorconfig" Link=".editorconfig" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj" />
</ItemGroup>

View File

@ -0,0 +1,157 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Odbc;
using System.Text;
namespace SqlSugar.GBase
{
/// <summary>
/// 数据填充器
/// </summary>
public class GBaseDataAdapter : IDataAdapter
{
private OdbcCommand command;
private string sql;
private OdbcConnection _sqlConnection;
/// <summary>
/// SqlDataAdapter
/// </summary>
/// <param name="command"></param>
public GBaseDataAdapter(OdbcCommand command)
{
this.command = command;
}
public GBaseDataAdapter()
{
}
/// <summary>
/// SqlDataAdapter
/// </summary>
/// <param name="sql"></param>
/// <param name="_sqlConnection"></param>
public GBaseDataAdapter(string sql, OdbcConnection _sqlConnection)
{
this.sql = sql;
this._sqlConnection = _sqlConnection;
}
/// <summary>
/// SelectCommand
/// </summary>
public OdbcCommand SelectCommand
{
get
{
if (this.command == null)
{
var conn = (OdbcConnection)this._sqlConnection;
this.command = conn.CreateCommand();
this.command.CommandText = sql;
}
return this.command;
}
set
{
this.command = value;
}
}
/// <summary>
/// Fill
/// </summary>
/// <param name="dt"></param>
public void Fill(DataTable dt)
{
if (dt == null)
{
dt = new DataTable();
}
var columns = dt.Columns;
var rows = dt.Rows;
using (var dr = command.ExecuteReader())
{
for (int i = 0; i < dr.FieldCount; i++)
{
string name = dr.GetName(i).Trim();
if (!columns.Contains(name))
columns.Add(new DataColumn(name, dr.GetFieldType(i)));
else
{
columns.Add(new DataColumn(name + i, dr.GetFieldType(i)));
}
}
while (dr.Read())
{
DataRow daRow = dt.NewRow();
for (int i = 0; i < columns.Count; i++)
{
daRow[columns[i].ColumnName] = dr.GetValue(i);
}
dt.Rows.Add(daRow);
}
}
dt.AcceptChanges();
}
/// <summary>
/// Fill
/// </summary>
/// <param name="ds"></param>
public void Fill(DataSet ds)
{
if (ds == null)
{
ds = new DataSet();
}
using (var dr = command.ExecuteReader())
{
do
{
var dt = new DataTable();
var columns = dt.Columns;
var rows = dt.Rows;
for (int i = 0; i < dr.FieldCount; i++)
{
string name = dr.GetName(i).Trim();
if (dr.GetFieldType(i).Name == "DateTime")
{
if (!columns.Contains(name))
columns.Add(new DataColumn(name, UtilConstants.DateType));
else
{
columns.Add(new DataColumn(name + i, UtilConstants.DateType));
}
}
else
{
if (!columns.Contains(name))
columns.Add(new DataColumn(name, dr.GetFieldType(i)));
else
{
columns.Add(new DataColumn(name + i, dr.GetFieldType(i)));
}
}
}
while (dr.Read())
{
DataRow daRow = dt.NewRow();
for (int i = 0; i < columns.Count; i++)
{
daRow[columns[i].ColumnName] = dr.GetValue(i);
}
dt.Rows.Add(daRow);
}
dt.AcceptChanges();
ds.Tables.Add(dt);
} while (dr.NextResult());
}
}
}
}

View File

@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
public class GBaseCodeFirst:CodeFirstProvider
{
protected override string GetTableName(EntityInfo entityInfo)
{
var table= this.Context.EntityMaintenance.GetTableName(entityInfo.EntityName);
var tableArray = table.Split('.');
var noFormat = table.Split(']').Length==1;
if (tableArray.Length > 1 && noFormat)
{
var dbMain = new GBaseDbMaintenance() { Context = this.Context };
var schmes = dbMain.GetSchemas();
if (!schmes.Any(it => it.EqualCase(tableArray.First())))
{
return tableArray.Last();
}
else
{
return dbMain.SqlBuilder.GetTranslationTableName(table);
}
}
else
{
return table;
}
}
}
}

View File

@ -0,0 +1,72 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
public class GBaseDbBind : DbBindProvider
{
public override string GetDbTypeName(string csharpTypeName)
{
if (csharpTypeName == nameof(DateTimeOffset))
{
return nameof(DateTimeOffset);
}
else
{
return base.GetDbTypeName(csharpTypeName);
}
}
public override List<KeyValuePair<string, CSharpDataType>> MappingTypes
{
get
{
var extService = this.Context.CurrentConnectionConfig.ConfigureExternalServices;
if (extService != null&& extService.AppendDataReaderTypeMappings.HasValue())
{
return extService.AppendDataReaderTypeMappings.Union(MappingTypesConst).ToList();
}
else
{
return MappingTypesConst;
}
}
}
public static List<KeyValuePair<string, CSharpDataType>> MappingTypesConst = new List<KeyValuePair<string, CSharpDataType>>()
{
new KeyValuePair<string, CSharpDataType>("int",CSharpDataType.@int),
new KeyValuePair<string, CSharpDataType>("varchar",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("nvarchar",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("sql_variant",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("text",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("char",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("ntext",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("nchar",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("hierarchyid",CSharpDataType.@string),
new KeyValuePair<string, CSharpDataType>("bigint",CSharpDataType.@long),
new KeyValuePair<string, CSharpDataType>("bit",CSharpDataType.@bool),
new KeyValuePair<string, CSharpDataType>("datetime",CSharpDataType.DateTime),
new KeyValuePair<string, CSharpDataType>("time",CSharpDataType.DateTime),
new KeyValuePair<string, CSharpDataType>("smalldatetime",CSharpDataType.DateTime),
new KeyValuePair<string, CSharpDataType>("timestamp",CSharpDataType.byteArray),
new KeyValuePair<string, CSharpDataType>("datetime2",CSharpDataType.DateTime),
new KeyValuePair<string, CSharpDataType>("date",CSharpDataType.DateTime),
new KeyValuePair<string, CSharpDataType>("decimal",CSharpDataType.@decimal),
new KeyValuePair<string, CSharpDataType>("single",CSharpDataType.@decimal),
new KeyValuePair<string, CSharpDataType>("money",CSharpDataType.@decimal),
new KeyValuePair<string, CSharpDataType>("numeric",CSharpDataType.@decimal),
new KeyValuePair<string, CSharpDataType>("smallmoney",CSharpDataType.@decimal),
new KeyValuePair<string, CSharpDataType>("float",CSharpDataType.@double),
new KeyValuePair<string, CSharpDataType>("float",CSharpDataType.Single),
new KeyValuePair<string, CSharpDataType>("real",CSharpDataType.@float),
new KeyValuePair<string, CSharpDataType>("smallint",CSharpDataType.@short),
new KeyValuePair<string, CSharpDataType>("tinyint",CSharpDataType.@byte),
new KeyValuePair<string, CSharpDataType>("uniqueidentifier",CSharpDataType.Guid),
new KeyValuePair<string, CSharpDataType>("binary",CSharpDataType.byteArray),
new KeyValuePair<string, CSharpDataType>("image",CSharpDataType.byteArray),
new KeyValuePair<string, CSharpDataType>("varbinary",CSharpDataType.byteArray),
new KeyValuePair<string, CSharpDataType>("datetimeoffset", CSharpDataType.DateTimeOffset),
new KeyValuePair<string, CSharpDataType>("datetimeoffset", CSharpDataType.DateTime)};
};
}

View File

@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
public class GBaseDbFirst : DbFirstProvider
{
}
}

View File

@ -0,0 +1,534 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
public class GBaseDbMaintenance : DbMaintenanceProvider
{
#region DML
protected override string GetDataBaseSql
{
get
{
return "SELECT NAME FROM master.dbo.sysdatabases ORDER BY NAME";
}
}
protected override string GetColumnInfosByTableNameSql
{
get
{
string sql = @"SELECT sysobjects.name AS TableName,
syscolumns.Id AS TableId,
syscolumns.name AS DbColumnName,
systypes.name AS DataType,
COLUMNPROPERTY(syscolumns.id,syscolumns.name,'PRECISION') as [length],
isnull(COLUMNPROPERTY(syscolumns.id,syscolumns.name,'Scale'),0) as Scale,
isnull(COLUMNPROPERTY(syscolumns.id,syscolumns.name,'Scale'),0) as DecimalDigits,
sys.extended_properties.[value] AS [ColumnDescription],
syscomments.text AS DefaultValue,
syscolumns.isnullable AS IsNullable,
columnproperty(syscolumns.id,syscolumns.name,'IsIdentity')as IsIdentity,
(CASE
WHEN EXISTS
(
select 1
from sysindexes i
join sysindexkeys k on i.id = k.id and i.indid = k.indid
join sysobjects o on i.id = o.id
join syscolumns c on i.id=c.id and k.colid = c.colid
where o.xtype = 'U'
and exists(select 1 from sysobjects where xtype = 'PK' and name = i.name)
and o.name=sysobjects.name and c.name=syscolumns.name
) THEN 1
ELSE 0
END) AS IsPrimaryKey
FROM syscolumns
INNER JOIN systypes ON syscolumns.xtype = systypes.xtype
LEFT JOIN sysobjects ON syscolumns.id = sysobjects.id
LEFT OUTER JOIN sys.extended_properties ON (sys.extended_properties.minor_id = syscolumns.colid
AND sys.extended_properties.major_id = syscolumns.id)
LEFT OUTER JOIN syscomments ON syscolumns.cdefault = syscomments.id
WHERE syscolumns.id IN
(SELECT id
FROM sysobjects
WHERE upper(xtype) IN('U',
'V') )
AND (systypes.name <> 'sysname')
AND sysobjects.name='{0}'
AND systypes.name<>'geometry'
AND systypes.name<>'geography'
ORDER BY syscolumns.colid";
return sql;
}
}
protected override string GetTableInfoListSql
{
get
{
return @"SELECT s.Name,Convert(varchar(max),tbp.value) as Description
FROM sysobjects s
LEFT JOIN sys.extended_properties as tbp ON s.id=tbp.major_id and tbp.minor_id=0 AND (tbp.Name='MS_Description' OR tbp.Name is null) WHERE s.xtype IN('U') ";
}
}
protected override string GetViewInfoListSql
{
get
{
return @"SELECT s.Name,Convert(varchar(max),tbp.value) as Description
FROM sysobjects s
LEFT JOIN sys.extended_properties as tbp ON s.id=tbp.major_id and tbp.minor_id=0 AND (tbp.Name='MS_Description' OR tbp.Name is null) WHERE s.xtype IN('V') ";
}
}
#endregion
#region DDL
protected override string CreateDataBaseSql
{
get
{
return @"create database {0} ";
}
}
protected override string AddPrimaryKeySql
{
get
{
return "ALTER TABLE {0} ADD CONSTRAINT {1} PRIMARY KEY({2})";
}
}
protected override string AddColumnToTableSql
{
get
{
return "ALTER TABLE {0} ADD {1} {2}{3} {4} {5} {6}";
}
}
protected override string AlterColumnToTableSql
{
get
{
return "ALTER TABLE {0} ALTER COLUMN {1} {2}{3} {4} {5} {6}";
}
}
protected override string BackupDataBaseSql
{
get
{
return @"USE master;BACKUP DATABASE {0} TO disk = '{1}'";
}
}
protected override string CreateTableSql
{
get
{
return "CREATE TABLE {0}(\r\n{1})";
}
}
protected override string CreateTableColumn
{
get
{
return "{0} {1}{2} {3} {4} {5}";
}
}
protected override string TruncateTableSql
{
get
{
return "TRUNCATE TABLE {0}";
}
}
protected override string BackupTableSql
{
get
{
return "SELECT TOP {0} * INTO {1} FROM {2}";
}
}
protected override string DropTableSql
{
get
{
return "DROP TABLE {0}";
}
}
protected override string DropColumnToTableSql
{
get
{
return "ALTER TABLE {0} DROP COLUMN {1}";
}
}
protected override string DropConstraintSql
{
get
{
return "ALTER TABLE {0} DROP CONSTRAINT {1}";
}
}
protected override string RenameColumnSql
{
get
{
return "exec sp_rename '{0}.{1}','{2}','column';";
}
}
protected override string AddColumnRemarkSql
{
get
{
return "EXECUTE sp_addextendedproperty N'MS_Description', N'{2}', N'user', N'dbo', N'table', N'{1}', N'column', N'{0}'"; ;
}
}
protected override string DeleteColumnRemarkSql
{
get
{
return "EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{1}','column','{0}'";
}
}
protected override string IsAnyColumnRemarkSql
{
get
{
return @"SELECT" +
" A.name AS table_name," +
" B.name AS column_name," +
" C.value AS column_description" +
" FROM sys.tables A" +
" LEFT JOIN sys.extended_properties C ON C.major_id = A.object_id" +
" LEFT JOIN sys.columns B ON B.object_id = A.object_id AND C.minor_id = B.column_id" +
" INNER JOIN sys.schemas SC ON SC.schema_id = A.schema_id AND SC.name = 'dbo'" +
" WHERE A.name = '{1}' and B.name = '{0}'";
}
}
protected override string AddTableRemarkSql
{
get
{
return "EXECUTE sp_addextendedproperty N'MS_Description', '{1}', N'user', N'dbo', N'table', N'{0}', NULL, NULL";
}
}
protected override string DeleteTableRemarkSql
{
get
{
return "EXEC sp_dropextendedproperty 'MS_Description','user',dbo,'table','{0}' ";
}
}
protected override string IsAnyTableRemarkSql
{
get
{
return @"SELECT C.class_desc
FROM sys.tables A
LEFT JOIN sys.extended_properties C ON C.major_id = A.object_id
INNER JOIN sys.schemas SC ON SC.schema_id=A.schema_id AND SC.name='dbo'
WHERE A.name = '{0}' AND minor_id=0";
}
}
protected override string RenameTableSql
{
get
{
return "EXEC sp_rename '{0}','{1}'";
}
}
protected override string CreateIndexSql
{
get
{
return "CREATE {3} NONCLUSTERED INDEX Index_{0}_{2} ON {0}({1})";
}
}
protected override string AddDefaultValueSql
{
get
{
return "alter table {0} ADD DEFAULT '{2}' FOR {1}";
}
}
protected override string IsAnyIndexSql
{
get
{
return "select count(*) from sys.indexes where name='{0}'";
}
}
#endregion
#region Check
protected override string CheckSystemTablePermissionsSql
{
get
{
return "select top 1 id from sysobjects";
}
}
#endregion
#region Scattered
protected override string CreateTableNull
{
get
{
return "NULL";
}
}
protected override string CreateTableNotNull
{
get
{
return "NOT NULL";
}
}
protected override string CreateTablePirmaryKey
{
get
{
return "PRIMARY KEY";
}
}
protected override string CreateTableIdentity
{
get
{
return "IDENTITY(1,1)";
}
}
#endregion
#region Methods
public override bool IsAnyTable(string tableName, bool isCache = true)
{
if (tableName.Contains("."))
{
var schemas = GetSchemas();
var first =this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').First());
var schemaInfo= schemas.FirstOrDefault(it=>it.EqualCase(first));
if (schemaInfo == null)
{
return base.IsAnyTable(tableName, isCache);
}
else
{
var result= this.Context.Ado.GetInt($"select object_id('{tableName}')");
return result > 0;
}
}
else
{
return base.IsAnyTable(tableName, isCache);
}
}
public List<string> GetSchemas()
{
return this.Context.Ado.SqlQuery<string>("SELECT name FROM sys.schemas where name <> 'dbo'");
}
public override bool DeleteTableRemark(string tableName)
{
string sql = string.Format(this.DeleteTableRemarkSql, tableName);
if (tableName.Contains("."))
{
var schemas = GetSchemas();
var tableSchemas = this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').First());
if (schemas.Any(y => y.EqualCase(tableSchemas)))
{
sql = string.Format(this.DeleteTableRemarkSql, this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').Last()));
if (tableSchemas.EqualCase("user"))
{
sql = sql.Replace("'user'", "'SCHEMA'").Replace("dbo", $"'{tableSchemas}'");
}
else
{
sql = sql.Replace(",dbo,", $",{tableSchemas},").Replace("'user'", "'SCHEMA'");
}
}
}
this.Context.Ado.ExecuteCommand(sql);
return true;
}
public override bool IsAnyTableRemark(string tableName)
{
string sql = string.Format(this.IsAnyTableRemarkSql, tableName);
if (tableName.Contains("."))
{
var schemas = GetSchemas();
var tableSchemas = this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').First());
if (schemas.Any(y => y.EqualCase(tableSchemas)))
{
sql = string.Format(this.IsAnyTableRemarkSql, this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').Last()));
sql = sql.Replace("'dbo'", $"'{tableSchemas}'");
}
}
var dt = this.Context.Ado.GetDataTable(sql);
return dt.Rows != null && dt.Rows.Count > 0;
}
public override bool AddTableRemark(string tableName, string description)
{
string sql = string.Format(this.AddTableRemarkSql, tableName, description);
if (tableName.Contains("."))
{
var schemas = GetSchemas();
var tableSchemas =this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').First());
if (schemas.Any(y => y.EqualCase(tableSchemas)))
{
sql = string.Format(this.AddTableRemarkSql, this.SqlBuilder.GetNoTranslationColumnName(tableName.Split('.').Last()), description);
if (tableSchemas.EqualCase("user"))
{
sql = sql.Replace("N'user', N'dbo'", $"N'user', '{tableSchemas}'").Replace("N'user'", "N'SCHEMA'");
}
else
{
sql = sql.Replace("N'dbo'", $"N'{tableSchemas}'").Replace("N'user'", "N'SCHEMA'");
}
}
}
this.Context.Ado.ExecuteCommand(sql);
return true;
}
public override bool AddDefaultValue(string tableName, string columnName, string defaultValue)
{
if (defaultValue == "''")
{
defaultValue = "";
}
var template = AddDefaultValueSql;
if (defaultValue != null && defaultValue.ToLower() == "getdate()")
{
template = template.Replace("'{2}'", "{2}");
}
string sql = string.Format(template, tableName, columnName, defaultValue);
this.Context.Ado.ExecuteCommand(sql);
return true;
}
/// <summary>
///by current connection string
/// </summary>
/// <param name="databaseDirectory"></param>
/// <returns></returns>
public override bool CreateDatabase(string databaseName, string databaseDirectory = null)
{
if (databaseDirectory != null)
{
try
{
if (!FileHelper.IsExistDirectory(databaseDirectory))
{
FileHelper.CreateDirectory(databaseDirectory);
}
}
catch
{
//Databases and sites are not in the same service
}
}
var oldDatabaseName = this.Context.Ado.Connection.Database;
var connection = this.Context.CurrentConnectionConfig.ConnectionString;
connection = connection.Replace(oldDatabaseName, "master");
var newDb = new SqlSugarClient(new ConnectionConfig()
{
DbType = this.Context.CurrentConnectionConfig.DbType,
IsAutoCloseConnection = true,
ConnectionString = connection
});
if (!GetDataBaseList(newDb).Any(it => it.Equals(databaseName, StringComparison.CurrentCultureIgnoreCase)))
{
var sql = CreateDataBaseSql;
if (databaseDirectory.HasValue())
{
sql += @"on primary
(
name = N'{0}',
filename = N'{1}\{0}.mdf',
size = 10mb,
maxsize = 100mb,
filegrowth = 1mb
),
(
name = N'{0}_ndf',
filename = N'{1}\{0}.ndf',
size = 10mb,
maxsize = 100mb,
filegrowth = 10 %
)
log on
(
name = N'{0}_log',
filename = N'{1}\{0}.ldf',
size = 100mb,
maxsize = 1gb,
filegrowth = 10mb
); ";
}
if (databaseName.Contains("."))
{
databaseName = $"[{databaseName}]";
}
newDb.Ado.ExecuteCommand(string.Format(sql, databaseName, databaseDirectory));
}
return true;
}
public override bool CreateTable(string tableName, List<DbColumnInfo> columns, bool isCreatePrimaryKey = true)
{
tableName = this.SqlBuilder.GetTranslationTableName(tableName);
foreach (var item in columns)
{
if (item.DataType == "decimal" && item.DecimalDigits == 0 && item.Length == 0)
{
item.DecimalDigits = 4;
item.Length = 18;
}
}
string sql = GetCreateTableSql(tableName, columns);
this.Context.Ado.ExecuteCommand(sql);
if (isCreatePrimaryKey)
{
var pkColumns = columns.Where(it => it.IsPrimarykey).ToList();
if (pkColumns.Count > 1)
{
this.Context.DbMaintenance.AddPrimaryKeys(tableName, pkColumns.Select(it => it.DbColumnName).ToArray());
}
else
{
foreach (var item in pkColumns)
{
this.Context.DbMaintenance.AddPrimaryKey(tableName, item.DbColumnName);
}
}
}
return true;
}
public override List<DbColumnInfo> GetColumnInfosByTableName(string tableName, bool isCache = true)
{
tableName = SqlBuilder.GetNoTranslationColumnName(tableName);
var result= base.GetColumnInfosByTableName(tableName, isCache);
return result;
}
public override bool RenameColumn(string tableName, string oldColumnName, string newColumnName)
{
tableName = this.SqlBuilder.GetTranslationTableName(tableName);
oldColumnName = this.SqlBuilder.GetTranslationColumnName(oldColumnName);
newColumnName = this.SqlBuilder.GetNoTranslationColumnName(newColumnName);
string sql = string.Format(this.RenameColumnSql, tableName, oldColumnName, newColumnName);
this.Context.Ado.ExecuteCommand(sql);
return true;
}
#endregion
}
}

View File

@ -0,0 +1,184 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Data.Odbc;
namespace SqlSugar.GBase
{
public class GBaseProvider : AdoProvider
{
public GBaseProvider() { }
public override IDbConnection Connection
{
get
{
if (base._DbConnection == null)
{
try
{
base._DbConnection = new OdbcConnection(base.Context.CurrentConnectionConfig.ConnectionString);
}
catch (Exception ex)
{
throw ex;
}
}
return base._DbConnection;
}
set
{
base._DbConnection = value;
}
}
/// <summary>
/// Only GBase
/// </summary>
/// <param name="transactionName"></param>
public override void BeginTran(string transactionName)
{
CheckConnection();
base.Transaction = ((OdbcConnection)this.Connection).BeginTransaction();
}
/// <summary>
/// Only GBase
/// </summary>
/// <param name="iso"></param>
/// <param name="transactionName"></param>
public override void BeginTran(IsolationLevel iso, string transactionName)
{
CheckConnection();
base.Transaction = ((OdbcConnection)this.Connection).BeginTransaction(iso);
}
public override IDataAdapter GetAdapter()
{
return new GBaseDataAdapter();
}
public override DbCommand GetCommand(string sql, SugarParameter[] parameters)
{
OdbcCommand sqlCommand = new OdbcCommand(sql, (OdbcConnection)this.Connection);
sqlCommand.CommandType = this.CommandType;
sqlCommand.CommandTimeout = this.CommandTimeOut;
if (this.Transaction != null)
{
sqlCommand.Transaction = (OdbcTransaction)this.Transaction;
}
if (parameters.HasValue())
{
OdbcParameter[] ipars = GetSqlParameter(parameters);
sqlCommand.Parameters.AddRange(ipars);
}
CheckConnection();
return sqlCommand;
}
public override void SetCommandToAdapter(IDataAdapter dataAdapter, DbCommand command)
{
((GBaseDataAdapter)dataAdapter).SelectCommand = (OdbcCommand)command;
}
/// <summary>
/// if mysql return MySqlParameter[] pars
/// if sqlerver return SqlParameter[] pars ...
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public override IDataParameter[] ToIDbDataParameter(params SugarParameter[] parameters)
{
if (parameters == null || parameters.Length == 0) return new OdbcParameter[] { };
OdbcParameter[] result = new OdbcParameter[parameters.Length];
int index = 0;
foreach (var parameter in parameters)
{
if (parameter.Value == null) parameter.Value = DBNull.Value;
var sqlParameter = new OdbcParameter();
sqlParameter.ParameterName = parameter.ParameterName;
//sqlParameter.UdtTypeName = parameter.UdtTypeName;
sqlParameter.Size = parameter.Size;
sqlParameter.Value = parameter.Value;
sqlParameter.DbType = parameter.DbType;
sqlParameter.Direction = parameter.Direction;
result[index] = sqlParameter;
if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput,ParameterDirection.ReturnValue))
{
if (this.OutputParameters == null) this.OutputParameters = new List<IDataParameter>();
this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName);
this.OutputParameters.Add(sqlParameter);
}
++index;
}
return result;
}
/// <summary>
/// if mysql return MySqlParameter[] pars
/// if sqlerver return SqlParameter[] pars ...
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public OdbcParameter[] GetSqlParameter(params SugarParameter[] parameters)
{
if (parameters == null || parameters.Length == 0) return null;
OdbcParameter[] result = new OdbcParameter[parameters.Length];
int index = 0;
foreach (var parameter in parameters)
{
if (parameter.Value == null) parameter.Value = DBNull.Value;
var sqlParameter = new OdbcParameter();
sqlParameter.ParameterName = parameter.ParameterName;
//sqlParameter.UdtTypeName = parameter.UdtTypeName;
sqlParameter.Size = parameter.Size;
sqlParameter.Value = parameter.Value;
sqlParameter.DbType = GetDbType(parameter);
var isTime = parameter.DbType == System.Data.DbType.Time;
if (isTime)
{
sqlParameter.Value = DateTime.Parse(parameter.Value?.ToString()).TimeOfDay;
}
if (sqlParameter.Value != null && sqlParameter.Value != DBNull.Value && sqlParameter.DbType == System.Data.DbType.DateTime)
{
var date = Convert.ToDateTime(sqlParameter.Value);
if (date == DateTime.MinValue)
{
sqlParameter.Value = UtilMethods.GetMinDate(this.Context.CurrentConnectionConfig);
}
}
if (parameter.Direction == 0)
{
parameter.Direction = ParameterDirection.Input;
}
sqlParameter.Direction = parameter.Direction;
result[index] = sqlParameter;
if (sqlParameter.Direction.IsIn(ParameterDirection.Output, ParameterDirection.InputOutput, ParameterDirection.ReturnValue))
{
if (this.OutputParameters == null) this.OutputParameters = new List<IDataParameter>();
this.OutputParameters.RemoveAll(it => it.ParameterName == sqlParameter.ParameterName);
this.OutputParameters.Add(sqlParameter);
}
++index;
}
return result;
}
private static System.Data.DbType GetDbType(SugarParameter parameter)
{
if (parameter.DbType==System.Data.DbType.UInt16)
{
return System.Data.DbType.Int16;
}
else if (parameter.DbType == System.Data.DbType.UInt32)
{
return System.Data.DbType.Int32;
}
else if (parameter.DbType == System.Data.DbType.UInt64)
{
return System.Data.DbType.Int64;
}
else
{
return parameter.DbType;
}
}
}
}

View File

@ -0,0 +1,58 @@
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace SqlSugar.GBase
{
public class GBaseQueryable<T>:QueryableProvider<T>
{
}
public class GBaseQueryable<T,T2> : QueryableProvider<T,T2>
{
}
public class GBaseQueryable<T, T2,T3> : QueryableProvider<T, T2,T3>
{
}
public class GBaseQueryable<T, T2,T3,T4> : QueryableProvider<T, T2,T3,T4>
{
}
public class GBaseQueryable<T, T2, T3, T4,T5> : QueryableProvider<T, T2, T3, T4,T5>
{
}
public class GBaseQueryable<T, T2, T3, T4, T5,T6> : QueryableProvider<T, T2, T3, T4, T5,T6>
{
}
public class GBaseQueryable<T, T2, T3, T4, T5, T6,T7> : QueryableProvider<T, T2, T3, T4, T5, T6,T7>
{
}
public class GBaseQueryable<T, T2, T3, T4, T5, T6, T7,T8> : QueryableProvider<T, T2, T3, T4, T5, T6, T7,T8>
{
}
public class GBaseQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9>
{
}
public class GBaseQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10>
{
}
public class GBaseQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>
{
}
public class GBaseQueryable<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : QueryableProvider<T, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>
{
}
}

View File

@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public class GBaseBlukCopy
{
internal List<IGrouping<int, DbColumnInfo>> DbColumnInfoList { get; set; }
internal SqlSugarProvider Context { get; set; }
internal ISqlBuilder Builder { get; set; }
internal InsertBuilder InsertBuilder { get; set; }
internal object[] Inserts { get; set; }
public int ExecuteBulkCopy()
{
if (DbColumnInfoList == null || DbColumnInfoList.Count == 0) return 0;
if (Inserts.First().GetType() == typeof(DataTable))
{
return WriteToServer();
}
DataTable dt = GetCopyData();
SqlBulkCopy bulkCopy = GetBulkCopyInstance();
bulkCopy.DestinationTableName = InsertBuilder.GetTableNameString;
try
{
bulkCopy.WriteToServer(dt);
}
catch (Exception ex)
{
CloseDb();
throw ex;
}
CloseDb();
return DbColumnInfoList.Count;
}
public async Task<int> ExecuteBulkCopyAsync()
{
if (DbColumnInfoList == null || DbColumnInfoList.Count == 0) return 0;
if (Inserts.First().GetType() == typeof(DataTable))
{
return WriteToServer();
}
DataTable dt=GetCopyData();
SqlBulkCopy bulkCopy = GetBulkCopyInstance();
bulkCopy.DestinationTableName = InsertBuilder.GetTableNameString;
try
{
await bulkCopy.WriteToServerAsync(dt);
}
catch (Exception ex)
{
CloseDb();
throw ex;
}
CloseDb();
return DbColumnInfoList.Count;
}
private int WriteToServer()
{
var dt = this.Inserts.First() as DataTable;
if (dt == null)
return 0;
Check.Exception(dt.TableName == "Table", "dt.TableName can't be null ");
dt = GetCopyWriteDataTable(dt);
SqlBulkCopy copy = GetBulkCopyInstance();
copy.DestinationTableName = this.Builder.GetTranslationColumnName(dt.TableName);
copy.WriteToServer(dt);
CloseDb();
return dt.Rows.Count;
}
private DataTable GetCopyWriteDataTable(DataTable dt)
{
var result = this.Context.Ado.GetDataTable("select top 0 * from " + this.Builder.GetTranslationColumnName(dt.TableName));
foreach (DataRow item in dt.Rows)
{
DataRow dr= result.NewRow();
foreach (DataColumn column in result.Columns)
{
if (dt.Columns.Cast<DataColumn>().Select(it => it.ColumnName.ToLower()).Contains(column.ColumnName.ToLower()))
{
dr[column.ColumnName] = item[column.ColumnName];
if (dr[column.ColumnName] == null)
{
dr[column.ColumnName] = DBNull.Value;
}
}
}
result.Rows.Add(dr);
}
result.TableName = dt.TableName;
return result;
}
private SqlBulkCopy GetBulkCopyInstance()
{
SqlBulkCopy copy;
if (this.Context.Ado.Transaction == null)
{
copy = new SqlBulkCopy((SqlConnection)this.Context.Ado.Connection);
}
else
{
copy = new SqlBulkCopy((SqlConnection)this.Context.Ado.Connection, SqlBulkCopyOptions.CheckConstraints, (SqlTransaction)this.Context.Ado.Transaction);
}
if (this.Context.Ado.Connection.State == ConnectionState.Closed)
{
this.Context.Ado.Connection.Open();
}
copy.BulkCopyTimeout = this.Context.Ado.CommandTimeOut;
return copy;
}
private DataTable GetCopyData()
{
var dt = this.Context.Ado.GetDataTable("select top 0 * from " + InsertBuilder.GetTableNameString);
foreach (var rowInfos in DbColumnInfoList)
{
var dr = dt.NewRow();
foreach (var value in rowInfos)
{
if (value.Value != null && UtilMethods.GetUnderType(value.Value.GetType()) == UtilConstants.DateType)
{
if (value.Value != null && value.Value.ToString() == DateTime.MinValue.ToString())
{
value.Value = Convert.ToDateTime("1753/01/01");
}
}
if (value.Value == null)
{
value.Value = DBNull.Value;
}
dr[value.DbColumnName] = value.Value;
}
dt.Rows.Add(dr);
}
return dt;
}
private void CloseDb()
{
if (this.Context.CurrentConnectionConfig.IsAutoCloseConnection && this.Context.Ado.Transaction == null)
{
this.Context.Ado.Connection.Close();
}
}
}
}

View File

@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public class GBaseBuilder : SqlBuilderProvider
{
public override string SqlTranslationLeft { get { return "["; } }
public override string SqlTranslationRight { get { return "]"; } }
}
}

View File

@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public class GBaseDeleteBuilder: DeleteBuilder
{
}
}

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public partial class GBaseExpressionContext : ExpressionContext, ILambdaExpressions
{
public SqlSugarProvider Context { get; set; }
public GBaseExpressionContext()
{
base.DbMehtods = new GBaseMethod();
}
}
public partial class GBaseMethod : DefaultDbMethod, IDbMethods
{
public override string GetForXmlPath()
{
return " FOR XML PATH('')),1,len(N','),'') ";
}
public override string GetStringJoinSelector(string result, string separator)
{
return $"stuff((SELECT cast(N'{separator}' as nvarchar(max)) + cast({result} as nvarchar(max))";
}
public override string DateValue(MethodCallExpressionModel model)
{
var parameter = model.Args[0];
var parameter2 = model.Args[1];
if (parameter.MemberName != null && parameter.MemberName is DateTime)
{
return string.Format(" datepart({0},'{1}') ", parameter2.MemberValue, parameter.MemberName);
}
else
{
return string.Format(" datepart({0},{1}) ", parameter2.MemberValue, parameter.MemberName);
}
}
public override string HasValue(MethodCallExpressionModel model)
{
if (model.Args[0].Type == UtilConstants.GuidType)
{
var parameter = model.Args[0];
return string.Format("( {0} IS NOT NULL )", parameter.MemberName);
}
else
{
var parameter = model.Args[0];
return string.Format("( {0}<>'' AND {0} IS NOT NULL )", parameter.MemberName);
}
}
}
}

View File

@ -0,0 +1,56 @@
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public class GBaseFastBuilder:FastBuilder,IFastBuilder
{
public override bool IsActionUpdateColumns { get; set; } = true;
public override DbFastestProperties DbFastestProperties { get; set; } = new DbFastestProperties() {
HasOffsetTime=true
};
public async Task<int> ExecuteBulkCopyAsync(DataTable dt)
{
SqlBulkCopy bulkCopy = GetBulkCopyInstance();
bulkCopy.DestinationTableName = dt.TableName;
try
{
await bulkCopy.WriteToServerAsync(dt);
}
catch (Exception ex)
{
CloseDb();
throw ex;
}
CloseDb();
return dt.Rows.Count;
}
public SqlBulkCopy GetBulkCopyInstance()
{
SqlBulkCopy copy;
if (this.Context.Ado.Transaction == null)
{
copy = new SqlBulkCopy((SqlConnection)this.Context.Ado.Connection);
}
else
{
copy = new SqlBulkCopy((SqlConnection)this.Context.Ado.Connection, SqlBulkCopyOptions.CheckConstraints, (SqlTransaction)this.Context.Ado.Transaction);
}
if (this.Context.Ado.Connection.State == ConnectionState.Closed)
{
this.Context.Ado.Connection.Open();
}
copy.BulkCopyTimeout = this.Context.Ado.CommandTimeOut;
return copy;
}
}
}

View File

@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public class GBaseInsertBuilder:InsertBuilder
{
public override string ToSqlString()
{
if (IsNoInsertNull)
{
DbColumnInfoList = DbColumnInfoList.Where(it => it.Value != null).ToList();
}
var groupList = DbColumnInfoList.GroupBy(it => it.TableId).ToList();
var isSingle = groupList.Count() == 1;
string columnsString = string.Join(",", groupList.First().Select(it => Builder.GetTranslationColumnName(it.DbColumnName)));
if (isSingle)
{
string columnParametersString = string.Join(",", this.DbColumnInfoList.Select(it => Builder.SqlParameterKeyWord + it.DbColumnName));
return string.Format(SqlTemplate, GetTableNameString, columnsString, columnParametersString);
}
else
{
StringBuilder batchInsetrSql = new StringBuilder();
int pageSize = 200;
if (this.EntityInfo.Columns.Count > 30)
{
pageSize = 50;
}
else if (this.EntityInfo.Columns.Count > 20)
{
pageSize = 100;
}
int pageIndex = 1;
int totalRecord = groupList.Count;
int pageCount = (totalRecord + pageSize - 1) / pageSize;
while (pageCount >= pageIndex)
{
batchInsetrSql.AppendFormat(SqlTemplateBatch, GetTableNameString, columnsString);
int i = 0;
foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
{
var isFirst = i == 0;
if (!isFirst)
{
batchInsetrSql.Append(SqlTemplateBatchUnion);
}
batchInsetrSql.Append("\r\n SELECT " + string.Join(",", columns.Select(it => string.Format(SqlTemplateBatchSelect, FormatValue(it.Value), Builder.GetTranslationColumnName(it.DbColumnName)))));
++i;
}
pageIndex++;
batchInsetrSql.Append("\r\n;\r\n");
}
var result = batchInsetrSql.ToString();
if (this.Context.CurrentConnectionConfig.DbType == DbType.GBase)
{
result += "select SCOPE_IDENTITY();";
}
return result;
}
}
}
}

View File

@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public class GBaseQueryBuilder: QueryBuilder
{
public override string SqlTemplate
{
get
{
return "SELECT {0}{"+UtilConstants.ReplaceKey+"} FROM {1}{2}{3}{4}";
}
}
public override string ToSqlString()
{
var oldTake = Take;
var oldSkip = Skip;
var isDistinctPage = IsDistinct && (Take > 1 || Skip > 1);
if (isDistinctPage)
{
Take = null;
Skip = null;
}
var result = _ToSqlString();
if (isDistinctPage)
{
if (this.OrderByValue.HasValue())
{
Take = int.MaxValue;
result = result.Replace("DISTINCT", $" DISTINCT TOP {int.MaxValue} ");
}
Take = oldTake;
Skip = oldSkip;
result =this.Context.SqlQueryable<object>(result).Skip(Skip??0).Take(Take??0).ToSql().Key;
}
if (result.IndexOf("-- No table") > 0)
{
return "-- No table";
}
return result;
}
public string _ToSqlString()
{
string oldOrderBy = this.OrderByValue;
string externalOrderBy = oldOrderBy;
var isIgnoreOrderBy = this.IsCount && this.PartitionByValue.IsNullOrEmpty();
AppendFilter();
sql = new StringBuilder();
var oldOrderByValue = this.OrderByValue;
if (this.OrderByValue == null && (Skip != null || Take != null)) this.OrderByValue = " ORDER BY GetDate() ";
if (this.PartitionByValue.HasValue())
{
this.OrderByValue = this.PartitionByValue + this.OrderByValue;
}
var isFirst = (Skip == 0 || Skip == null) && Take == 1 && DisableTop == false;
var isTop = (Skip == null && Take != null && DisableTop == false);
var isRowNumber = (Skip != null || Take != null) && !isFirst && !isTop;
if (!isRowNumber && oldOrderByValue == null) { this.OrderByValue = null; }
if (isFirst && oldOrderByValue == "ORDER BY GETDATE() ") { this.OrderByValue = null; }
var rowNumberString = string.Format(",ROW_NUMBER() OVER({0}) AS RowIndex ", GetOrderByString);
string groupByValue = GetGroupByString + HavingInfos;
string orderByValue = (!isRowNumber && this.OrderByValue.HasValue()) ? GetOrderByString : null;
if (isIgnoreOrderBy) { orderByValue = null; }
sql.AppendFormat(SqlTemplate, GetSelect(isFirst,isTop), base.GetTableNameString, base.GetWhereValueString, groupByValue, orderByValue);
sql.Replace(UtilConstants.ReplaceKey, isRowNumber ? (isIgnoreOrderBy ? null : rowNumberString) : null);
if (isIgnoreOrderBy) { this.OrderByValue = oldOrderBy; return sql.ToString(); }
var result = (isFirst || isTop) ? sql.ToString() : ToPageSql(sql.ToString(), this.Take, this.Skip);
if (ExternalPageIndex > 0)
{
if (externalOrderBy.IsNullOrEmpty())
{
externalOrderBy = " ORDER BY GetDate() ";
}
result = string.Format("SELECT *,ROW_NUMBER() OVER({0}) AS RowIndex2 FROM ({1}) ExternalTable ", GetExternalOrderBy(externalOrderBy), result);
result = ToPageSql2(result, ExternalPageIndex, ExternalPageSize, true);
}
this.OrderByValue = oldOrderBy;
if (!string.IsNullOrEmpty(this.Offset))
{
if (this.OrderByValue.IsNullOrEmpty())
{
result += " ORDER BY GETDATE() ";
if (this.OldSql.HasValue())
this.OldSql += " ORDER BY GETDATE() ";
}
else
{
if (this.OldSql.HasValue())
this.OldSql += (" " + this.GetOrderByString);
}
result += this.Offset;
if (this.OldSql.HasValue())
this.OldSql += this.Offset;
}
result = GetSqlQuerySql(result);
return result;
}
private string GetSelect(bool isFirst,bool isTop)
{
if (isFirst)
{
return (" TOP 1 " + GetSelectValue);
}
else if(isTop)
{
return ($" TOP {this.Take} " + GetSelectValue);
}
else
{
return GetSelectValue;
}
}
}
}

View File

@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace SqlSugar.GBase
{
public class GBaseUpdateBuilder: UpdateBuilder
{
protected override string TomultipleSqlString(List<IGrouping<int, DbColumnInfo>> groupList)
{
Check.Exception(PrimaryKeys == null || PrimaryKeys.Count == 0, " Update List<T> need Primary key");
int pageSize = 200;
int pageIndex = 1;
int totalRecord = groupList.Count;
int pageCount = (totalRecord + pageSize - 1) / pageSize;
StringBuilder batchUpdateSql = new StringBuilder();
while (pageCount >= pageIndex)
{
StringBuilder updateTable = new StringBuilder();
string setValues = string.Join(",", groupList.First().Where(it => it.IsPrimarykey == false && (it.IsIdentity == false || (IsOffIdentity && it.IsIdentity))).Select(it =>
{
if (SetValues.IsValuable())
{
var setValue = SetValues.Where(sv => sv.Key == Builder.GetTranslationColumnName(it.DbColumnName));
if (setValue != null && setValue.Any())
{
return setValue.First().Value;
}
}
var result = string.Format("S.{0}=T.{0}", Builder.GetTranslationColumnName(it.DbColumnName));
return result;
}));
batchUpdateSql.AppendFormat(SqlTemplateBatch.ToString(), setValues, GetTableNameStringNoWith, TableWithString);
int i = 0;
foreach (var columns in groupList.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList())
{
var isFirst = i == 0;
if (!isFirst)
{
updateTable.Append(SqlTemplateBatchUnion);
}
updateTable.Append("\r\n SELECT " + string.Join(",", columns.Select(it => string.Format(base.SqlTemplateBatchSelect, GetValue(it), Builder.GetTranslationColumnName(it.DbColumnName)))));
++i;
}
pageIndex++;
updateTable.Append("\r\n");
string whereString = null;
if (this.WhereValues.HasValue())
{
foreach (var item in WhereValues)
{
var isFirst = whereString == null;
whereString += (isFirst ? null : " AND ");
whereString += Regex.Replace(item, "\\" + this.Builder.SqlTranslationLeft, "S." + this.Builder.SqlTranslationLeft);
}
}
if (PrimaryKeys!=null&&PrimaryKeys.HasValue())
{
foreach (var item in PrimaryKeys)
{
var isFirst = whereString == null;
whereString += (isFirst ? null : " AND ");
whereString += string.Format("S.{0}=T.{0}", Builder.GetTranslationColumnName(item));
}
}
batchUpdateSql.AppendFormat(SqlTemplateJoin, updateTable, whereString);
}
return batchUpdateSql.ToString();
}
private object GetValue(DbColumnInfo it)
{
return FormatValue(it.Value);
}
}
}

View File

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Data.Odbc" Version="4.6.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SqlSugar\SqlSugar.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
internal static partial class ErrorMessage
{
internal static LanguageType SugarLanguageType { get; set; } = LanguageType.Default;
internal static string ObjNotExist
{
get
{
return GetThrowMessage("{0} does not exist.",
"{0}不存在。");
}
}
internal static string EntityMappingError
{
get
{
return GetThrowMessage("Entity mapping error.{0}",
"实体与表映射出错。{0}");
}
}
public static string NotSupportedDictionary
{
get
{
return GetThrowMessage("This type of Dictionary is not supported for the time being. You can try Dictionary<string, string>, or contact the author!!",
"暂时不支持该类型的Dictionary 你可以试试 Dictionary<string ,string>或者联系作者!!");
}
}
public static string NotSupportedArray
{
get
{
return GetThrowMessage("This type of Array is not supported for the time being. You can try object[] or contact the author!!",
"暂时不支持该类型的Array 你可以试试 object[] 或者联系作者!!");
}
}
internal static string GetThrowMessage(string enMessage, string cnMessage, params string[] args)
{
if (SugarLanguageType == LanguageType.Default)
{
List<string> formatArgs = new List<string>() { enMessage, cnMessage };
formatArgs.AddRange(args);
return string.Format(@"中文提示 : {1}
English Message : {0}", formatArgs.ToArray());
}
else if (SugarLanguageType == LanguageType.English)
{
return enMessage;
}
else
{
return cnMessage;
}
}
}
}

View File

@ -0,0 +1,70 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
internal class FileHelper
{
public static void CreateFile(string filePath, string text, Encoding encoding)
{
try
{
if (IsExistFile(filePath))
{
DeleteFile(filePath);
}
if (!IsExistFile(filePath))
{
string directoryPath = GetDirectoryFromFilePath(filePath);
CreateDirectory(directoryPath);
//Create File
FileInfo file = new FileInfo(filePath);
using (FileStream stream = file.Create())
{
using (StreamWriter writer = new StreamWriter(stream, encoding))
{
writer.Write(text);
writer.Flush();
}
}
}
}
catch(Exception ex)
{
throw ex;
}
}
public static bool IsExistDirectory(string directoryPath)
{
return Directory.Exists(directoryPath);
}
public static void CreateDirectory(string directoryPath)
{
if (!IsExistDirectory(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
}
public static void DeleteFile(string filePath)
{
if (IsExistFile(filePath))
{
File.Delete(filePath);
}
}
public static string GetDirectoryFromFilePath(string filePath)
{
FileInfo file = new FileInfo(filePath);
DirectoryInfo directory = file.Directory;
return directory.FullName;
}
public static bool IsExistFile(string filePath)
{
return File.Exists(filePath);
}
}
}

View File

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
internal static class UtilConstants
{
public const string Dot = ".";
public const char DotChar = '.';
internal const string Space = " ";
internal const char SpaceChar =' ';
internal const string AssemblyName = "SqlSugar";
internal const string ReplaceKey = "{662E689B-17A1-4D06-9D27-F29EAB8BC3D6}";
internal const string ReplaceCommaKey = "{112A689B-17A1-4A06-9D27-A39EAB8BC3D5}";
internal static Type IntType = typeof(int);
internal static Type LongType = typeof(long);
internal static Type GuidType = typeof(Guid);
internal static Type BoolType = typeof(bool);
internal static Type BoolTypeNull = typeof(bool?);
internal static Type ByteType = typeof(Byte);
internal static Type ObjType = typeof(object);
internal static Type DobType = typeof(double);
internal static Type FloatType = typeof(float);
internal static Type ShortType = typeof(short);
internal static Type DecType = typeof(decimal);
internal static Type StringType = typeof(string);
internal static Type DateType = typeof(DateTime);
internal static Type DateTimeOffsetType = typeof(DateTimeOffset);
internal static Type TimeSpanType = typeof(TimeSpan);
internal static Type ByteArrayType = typeof(byte[]);
internal static Type ModelType= typeof(ModelContext);
internal static Type DynamicType = typeof(ExpandoObject);
internal static Type Dicii = typeof(KeyValuePair<int, int>);
internal static Type DicIS = typeof(KeyValuePair<int, string>);
internal static Type DicSi = typeof(KeyValuePair<string, int>);
internal static Type DicSS = typeof(KeyValuePair<string, string>);
internal static Type DicOO = typeof(KeyValuePair<object, object>);
internal static Type DicSo = typeof(KeyValuePair<string, object>);
internal static Type DicArraySS = typeof(Dictionary<string, string>);
internal static Type DicArraySO = typeof(Dictionary<string, object>);
public static Type SugarType = typeof(SqlSugarProvider);
internal static Type[] NumericalTypes = new Type[]
{
typeof(int),
typeof(uint),
typeof(byte),
typeof(sbyte),
typeof(long),
typeof(ulong),
typeof(short),
typeof(ushort),
};
internal static string[] DateTypeStringList = new string[]
{
"Year",
"Month",
"Day",
"Hour",
"Second" ,
"Minute",
"Millisecond",
"Date"
};
}
}

View File

@ -0,0 +1,142 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SqlSugar.GBase
{
/// <summary>
///Common Extensions for external users
/// </summary>
public static class UtilExtensions
{
public static bool EqualCase(this string thisValue, string equalValue)
{
if (thisValue != null && equalValue != null)
{
return thisValue.ToLower() == equalValue.ToLower();
}
else
{
return thisValue == equalValue;
}
}
public static string ToLower(this string value, bool isLower)
{
if (isLower)
{
return value.ObjToString().ToLower();
}
return value.ObjToString();
}
public static int ObjToInt(this object thisValue)
{
int reval = 0;
if (thisValue == null) return 0;
if (thisValue is Enum)
{
return (int)thisValue;
}
if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
public static int ObjToInt(this object thisValue, int errorValue)
{
int reval = 0;
if (thisValue is Enum)
{
return (int)thisValue;
}
if (thisValue != null && thisValue != DBNull.Value && int.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
public static double ObjToMoney(this object thisValue)
{
double reval = 0;
if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return 0;
}
public static double ObjToMoney(this object thisValue, double errorValue)
{
double reval = 0;
if (thisValue != null && thisValue != DBNull.Value && double.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
public static string ObjToString(this object thisValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return "";
}
public static string ObjToString(this object thisValue, string errorValue)
{
if (thisValue != null) return thisValue.ToString().Trim();
return errorValue;
}
public static Decimal ObjToDecimal(this object thisValue)
{
Decimal reval = 0;
if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return 0;
}
public static Decimal ObjToDecimal(this object thisValue, decimal errorValue)
{
Decimal reval = 0;
if (thisValue != null && thisValue != DBNull.Value && decimal.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
public static DateTime ObjToDate(this object thisValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
reval = Convert.ToDateTime(thisValue);
}
return reval;
}
public static DateTime ObjToDate(this object thisValue, DateTime errorValue)
{
DateTime reval = DateTime.MinValue;
if (thisValue != null && thisValue != DBNull.Value && DateTime.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return errorValue;
}
public static bool ObjToBool(this object thisValue)
{
bool reval = false;
if (thisValue != null && thisValue != DBNull.Value && bool.TryParse(thisValue.ToString(), out reval))
{
return reval;
}
return reval;
}
}
}

View File

@ -0,0 +1,507 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
namespace SqlSugar.GBase
{
public class UtilMethods
{
internal static DateTime GetMinDate(ConnectionConfig currentConnectionConfig)
{
if (currentConnectionConfig.MoreSettings == null)
{
return Convert.ToDateTime("1900-01-01");
}
else if (currentConnectionConfig.MoreSettings.DbMinDate == null)
{
return Convert.ToDateTime("1900-01-01");
}
else
{
return currentConnectionConfig.MoreSettings.DbMinDate.Value;
}
}
internal static DateTime ConvertFromDateTimeOffset(DateTimeOffset dateTime)
{
if (dateTime.Offset.Equals(TimeSpan.Zero))
return dateTime.UtcDateTime;
else if (dateTime.Offset.Equals(TimeZoneInfo.Local.GetUtcOffset(dateTime.DateTime)))
return DateTime.SpecifyKind(dateTime.DateTime, DateTimeKind.Local);
else
return dateTime.DateTime;
}
internal static object To(object value, Type destinationType)
{
return To(value, destinationType, CultureInfo.InvariantCulture);
}
internal static object To(object value, Type destinationType, CultureInfo culture)
{
if (value != null)
{
destinationType = UtilMethods.GetUnderType(destinationType);
var sourceType = value.GetType();
var destinationConverter = TypeDescriptor.GetConverter(destinationType);
if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
return destinationConverter.ConvertFrom(null, culture, value);
var sourceConverter = TypeDescriptor.GetConverter(sourceType);
if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
return sourceConverter.ConvertTo(null, culture, value, destinationType);
if (destinationType.IsEnum && value is int)
return Enum.ToObject(destinationType, (int)value);
if (!destinationType.IsInstanceOfType(value))
return Convert.ChangeType(value, destinationType, culture);
}
return value;
}
public static bool IsAnyAsyncMethod(StackFrame[] methods)
{
bool isAsync = false;
foreach (var item in methods)
{
if (UtilMethods.IsAsyncMethod(item.GetMethod()))
{
isAsync = true;
break;
}
}
return isAsync;
}
public static bool IsAsyncMethod(MethodBase method)
{
if (method == null)
{
return false;
}
if (method.DeclaringType != null)
{
if (method.DeclaringType.GetInterfaces().Contains(typeof(IAsyncStateMachine)))
{
return true;
}
}
var name = method.Name;
if (name.Contains("OutputAsyncCausalityEvents"))
{
return true;
}
if (name.Contains("OutputWaitEtwEvents"))
{
return true;
}
if (name.Contains("ExecuteAsync"))
{
return true;
}
Type attType = typeof(AsyncStateMachineAttribute);
var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);
return (attrib != null);
}
public static StackTraceInfo GetStackTrace()
{
StackTrace st = new StackTrace(true);
StackTraceInfo info = new StackTraceInfo();
info.MyStackTraceList = new List<StackTraceInfoItem>();
info.SugarStackTraceList = new List<StackTraceInfoItem>();
for (int i = 0; i < st.FrameCount; i++)
{
var frame = st.GetFrame(i);
if (frame.GetMethod().Module.Name.ToLower() != "sqlsugar.dll" && frame.GetMethod().Name.First() != '<')
{
info.MyStackTraceList.Add(new StackTraceInfoItem()
{
FileName = frame.GetFileName(),
MethodName = frame.GetMethod().Name,
Line = frame.GetFileLineNumber()
});
}
else
{
info.SugarStackTraceList.Add(new StackTraceInfoItem()
{
FileName = frame.GetFileName(),
MethodName = frame.GetMethod().Name,
Line = frame.GetFileLineNumber()
});
}
}
return info;
}
internal static T To<T>(object value)
{
return (T)To(value, typeof(T));
}
internal static Type GetUnderType(Type oldType)
{
Type type = Nullable.GetUnderlyingType(oldType);
return type == null ? oldType : type;
}
public static string ReplaceSqlParameter(string itemSql, SugarParameter itemParameter, string newName)
{
itemSql = Regex.Replace(itemSql, string.Format(@"{0} ", "\\" + itemParameter.ParameterName), newName + " ", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"{0}\)", "\\" + itemParameter.ParameterName), newName + ")", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"{0}\,", "\\" + itemParameter.ParameterName), newName + ",", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"{0}$", "\\" + itemParameter.ParameterName), newName, RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\+{0}\+", "\\" + itemParameter.ParameterName), "+" + newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\+{0} ", "\\" + itemParameter.ParameterName), "+" + newName + " ", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@" {0}\+", "\\" + itemParameter.ParameterName), " " + newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\|\|{0}\|\|", "\\" + itemParameter.ParameterName), "||" + newName + "||", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"\={0}\+", "\\" + itemParameter.ParameterName), "=" + newName + "+", RegexOptions.IgnoreCase);
itemSql = Regex.Replace(itemSql, string.Format(@"{0}\|\|", "\\" + itemParameter.ParameterName), newName + "||", RegexOptions.IgnoreCase);
return itemSql;
}
internal static Type GetRootBaseType(Type entityType)
{
var baseType = entityType.BaseType;
while (baseType != null && baseType.BaseType != UtilConstants.ObjType)
{
baseType = baseType.BaseType;
}
return baseType;
}
internal static Type GetUnderType(PropertyInfo propertyInfo, ref bool isNullable)
{
Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
isNullable = unType != null;
unType = unType ?? propertyInfo.PropertyType;
return unType;
}
internal static Type GetUnderType(PropertyInfo propertyInfo)
{
Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
unType = unType ?? propertyInfo.PropertyType;
return unType;
}
internal static bool IsNullable(PropertyInfo propertyInfo)
{
Type unType = Nullable.GetUnderlyingType(propertyInfo.PropertyType);
return unType != null;
}
internal static bool IsNullable(Type type)
{
Type unType = Nullable.GetUnderlyingType(type);
return unType != null;
}
//internal static T IsNullReturnNew<T>(T returnObj) where T : new()
//{
// if (returnObj.IsNullOrEmpty())
// {
// returnObj = new T();
// }
// return returnObj;
//}
public static object ChangeType2(object value, Type type)
{
if (value == null && type.IsGenericType) return Activator.CreateInstance(type);
if (value == null) return null;
if (type == value.GetType()) return value;
if (type.IsEnum)
{
if (value is string)
return Enum.Parse(type, value as string);
else
return Enum.ToObject(type, value);
}
if (!type.IsInterface && type.IsGenericType)
{
Type innerType = type.GetGenericArguments()[0];
object innerValue = ChangeType(value, innerType);
return Activator.CreateInstance(type, new object[] { innerValue });
}
if (value is string && type == typeof(Guid)) return new Guid(value as string);
if (value is string && type == typeof(Version)) return new Version(value as string);
if (!(value is IConvertible)) return value;
return Convert.ChangeType(value, type);
}
internal static T ChangeType<T>(T obj, Type type)
{
return (T)Convert.ChangeType(obj, type);
}
internal static T ChangeType<T>(T obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}
internal static DateTimeOffset GetDateTimeOffsetByDateTime(DateTime date)
{
date = DateTime.SpecifyKind(date, DateTimeKind.Utc);
DateTimeOffset utcTime2 = date;
return utcTime2;
}
//internal static void RepairReplicationParameters(ref string appendSql, SugarParameter[] parameters, int addIndex, string append = null)
//{
// if (appendSql.HasValue() && parameters.HasValue())
// {
// foreach (var parameter in parameters.OrderByDescending(it => it.ParameterName.Length))
// {
// //Compatible with.NET CORE parameters case
// var name = parameter.ParameterName;
// string newName = name + append + addIndex;
// appendSql = ReplaceSqlParameter(appendSql, parameter, newName);
// parameter.ParameterName = newName;
// }
// }
//}
internal static string GetPackTable(string sql, string shortName)
{
return string.Format(" ({0}) {1} ", sql, shortName);
}
public static Func<string, object> GetTypeConvert(object value)
{
if (value is int || value is uint || value is int? || value is uint?)
{
return x => Convert.ToInt32(x);
}
else if (value is short || value is ushort || value is short? || value is ushort?)
{
return x => Convert.ToInt16(x);
}
else if (value is long || value is long? || value is ulong? || value is long?)
{
return x => Convert.ToInt64(x);
}
else if (value is DateTime|| value is DateTime?)
{
return x => Convert.ToDateTime(x);
}
else if (value is bool||value is bool?)
{
return x => Convert.ToBoolean(x);
}
return null;
}
internal static string GetTypeName(object value)
{
if (value == null)
{
return null;
}
else
{
return value.GetType().Name;
}
}
internal static string GetParenthesesValue(string dbTypeName)
{
if (Regex.IsMatch(dbTypeName, @"\(.+\)"))
{
dbTypeName = Regex.Replace(dbTypeName, @"\(.+\)", "");
}
dbTypeName = dbTypeName.Trim();
return dbTypeName;
}
internal static T GetOldValue<T>(T value, Action action)
{
action();
return value;
}
internal static object DefaultForType(Type targetType)
{
return targetType.IsValueType ? Activator.CreateInstance(targetType) : null;
}
internal static Int64 GetLong(byte[] bytes)
{
return Convert.ToInt64(string.Join("", bytes).PadRight(20, '0'));
}
public static object GetPropertyValue<T>(T t, string PropertyName)
{
return t.GetType().GetProperty(PropertyName).GetValue(t, null);
}
internal static string GetMD5(string myString)
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] fromData = System.Text.Encoding.Unicode.GetBytes(myString);
byte[] targetData = md5.ComputeHash(fromData);
string byte2String = null;
for (int i = 0; i < targetData.Length; i++)
{
byte2String += targetData[i].ToString("x");
}
return byte2String;
}
//public static string EncodeBase64(string code)
//{
// if (code.IsNullOrEmpty()) return code;
// string encode = "";
// byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(code);
// try
// {
// encode = Convert.ToBase64String(bytes);
// }
// catch
// {
// encode = code;
// }
// return encode;
//}
public static string ConvertNumbersToString(string value)
{
string[] splitInt = value.Split(new char[] { '9' }, StringSplitOptions.RemoveEmptyEntries);
var splitChars = splitInt.Select(s => Convert.ToChar(
Convert.ToInt32(s, 8)
).ToString());
return string.Join("", splitChars);
}
public static string ConvertStringToNumbers(string value)
{
StringBuilder sb = new StringBuilder();
foreach (char c in value)
{
int cAscil = (int)c;
sb.Append(Convert.ToString(c, 8) + "9");
}
return sb.ToString();
}
//public static string DecodeBase64(string code)
//{
// try
// {
// if (code.IsNullOrEmpty()) return code;
// string decode = "";
// byte[] bytes = Convert.FromBase64String(code);
// try
// {
// decode = Encoding.GetEncoding("utf-8").GetString(bytes);
// }
// catch
// {
// decode = code;
// }
// return decode;
// }
// catch
// {
// return code;
// }
//}
public static void DataInoveByExpresson<Type>(Type[] datas, MethodCallExpression callExpresion)
{
var methodInfo = callExpresion.Method;
foreach (var item in datas)
{
if (callExpresion.Arguments.Count == 0)
{
methodInfo.Invoke(item, null);
}
else
{
List<object> methodParameters = new List<object>();
foreach (var callItem in callExpresion.Arguments)
{
var parameter = callItem.GetType().GetProperties().FirstOrDefault(it => it.Name == "Value");
if (parameter == null)
{
var value = LambdaExpression.Lambda(callItem).Compile().DynamicInvoke();
methodParameters.Add(value);
}
else
{
var value = parameter.GetValue(callItem, null);
methodParameters.Add(value);
}
}
methodInfo.Invoke(item, methodParameters.ToArray());
}
}
}
public static Dictionary<string, T> EnumToDictionary<T>()
{
Dictionary<string, T> dic = new Dictionary<string, T>();
if (!typeof(T).IsEnum)
{
return dic;
}
string desc = string.Empty;
foreach (var item in Enum.GetValues(typeof(T)))
{
var key = item.ToString().ToLower();
if (!dic.ContainsKey(key))
dic.Add(key, (T)item);
}
return dic;
}
//public static object ConvertDataByTypeName(string ctypename,string value)
//{
// var item = new ConditionalModel() {
// CSharpTypeName = ctypename,
// FieldValue = value
// };
// if (item.CSharpTypeName.EqualCase(UtilConstants.DecType.Name))
// {
// return Convert.ToDecimal(item.FieldValue);
// }
// else if (item.CSharpTypeName.EqualCase(UtilConstants.DobType.Name))
// {
// return Convert.ToDouble(item.FieldValue);
// }
// else if (item.CSharpTypeName.EqualCase(UtilConstants.DateType.Name))
// {
// return Convert.ToDateTime(item.FieldValue);
// }
// else if (item.CSharpTypeName.EqualCase(UtilConstants.IntType.Name))
// {
// return Convert.ToInt32(item.FieldValue);
// }
// else if (item.CSharpTypeName.EqualCase(UtilConstants.LongType.Name))
// {
// return Convert.ToInt64(item.FieldValue);
// }
// else if (item.CSharpTypeName.EqualCase(UtilConstants.ShortType.Name))
// {
// return Convert.ToInt16(item.FieldValue);
// }
// else if (item.CSharpTypeName.EqualCase(UtilConstants.DateTimeOffsetType.Name))
// {
// return UtilMethods.GetDateTimeOffsetByDateTime(Convert.ToDateTime(item.FieldValue));
// }
// else
// {
// return item.FieldValue;
// }
//}
}
}

View File

@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace SqlSugar.GBase
{
internal static class ValidateExtensions
{
public static bool IsInRange(this int thisValue, int begin, int end)
{
return thisValue >= begin && thisValue <= end;
}
public static bool IsInRange(this DateTime thisValue, DateTime begin, DateTime end)
{
return thisValue >= begin && thisValue <= end;
}
public static bool IsIn<T>(this T thisValue, params T[] values)
{
return values.Contains(thisValue);
}
public static bool IsContainsIn(this string thisValue, params string[] inValues)
{
return inValues.Any(it => thisValue.Contains(it));
}
public static bool IsNullOrEmpty(this object thisValue)
{
if (thisValue == null || thisValue == DBNull.Value) return true;
return thisValue.ToString() == "";
}
public static bool IsNullOrEmpty(this Guid? thisValue)
{
if (thisValue == null) return true;
return thisValue == Guid.Empty;
}
public static bool IsNullOrEmpty(this Guid thisValue)
{
if (thisValue == null) return true;
return thisValue == Guid.Empty;
}
public static bool IsNullOrEmpty(this IEnumerable<object> thisValue)
{
if (thisValue == null || thisValue.Count() == 0) return true;
return false;
}
public static bool HasValue(this object thisValue)
{
if (thisValue == null || thisValue == DBNull.Value) return false;
return thisValue.ToString() != "";
}
public static bool HasValue(this IEnumerable<object> thisValue)
{
if (thisValue == null || thisValue.Count() == 0) return false;
return true;
}
public static bool IsValuable(this IEnumerable<KeyValuePair<string,string>> thisValue)
{
if (thisValue == null || thisValue.Count() == 0) return false;
return true;
}
public static bool IsZero(this object thisValue)
{
return (thisValue == null || thisValue.ToString() == "0");
}
public static bool IsInt(this object thisValue)
{
if (thisValue == null) return false;
return Regex.IsMatch(thisValue.ToString(), @"^\d+$");
}
/// <returns></returns>
public static bool IsNoInt(this object thisValue)
{
if (thisValue == null) return true;
return !Regex.IsMatch(thisValue.ToString(), @"^\d+$");
}
public static bool IsMoney(this object thisValue)
{
if (thisValue == null) return false;
double outValue = 0;
return double.TryParse(thisValue.ToString(), out outValue);
}
public static bool IsGuid(this object thisValue)
{
if (thisValue == null) return false;
Guid outValue = Guid.Empty;
return Guid.TryParse(thisValue.ToString(), out outValue);
}
public static bool IsDate(this object thisValue)
{
if (thisValue == null) return false;
DateTime outValue = DateTime.MinValue;
return DateTime.TryParse(thisValue.ToString(), out outValue);
}
public static bool IsEamil(this object thisValue)
{
if (thisValue == null) return false;
return Regex.IsMatch(thisValue.ToString(), @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$");
}
public static bool IsMobile(this object thisValue)
{
if (thisValue == null) return false;
return Regex.IsMatch(thisValue.ToString(), @"^\d{11}$");
}
public static bool IsTelephone(this object thisValue)
{
if (thisValue == null) return false;
return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{8}$");
}
public static bool IsIDcard(this object thisValue)
{
if (thisValue == null) return false;
return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$");
}
public static bool IsFax(this object thisValue)
{
if (thisValue == null) return false;
return System.Text.RegularExpressions.Regex.IsMatch(thisValue.ToString(), @"^[+]{0,1}(\d){1,3}[ ]?([-]?((\d)|[ ]){1,12})+$");
}
public static bool IsMatch(this object thisValue, string pattern)
{
if (thisValue == null) return false;
Regex reg = new Regex(pattern);
return reg.IsMatch(thisValue.ToString());
}
public static bool IsAnonymousType(this Type type)
{
string typeName = type.Name;
return typeName.Contains("<>") && typeName.Contains("__") && typeName.Contains("AnonymousType");
}
public static bool IsCollectionsList(this string thisValue)
{
return (thisValue + "").StartsWith("System.Collections.Generic.List")|| (thisValue + "").StartsWith("System.Collections.Generic.IEnumerable");
}
public static bool IsStringArray(this string thisValue)
{
return (thisValue + "").IsMatch(@"System\.[a-z,A-Z,0-9]+?\[\]");
}
public static bool IsEnumerable(this string thisValue)
{
return (thisValue + "").StartsWith("System.Linq.Enumerable");
}
public static Type StringType = typeof (string);
public static bool IsClass(this Type thisValue)
{
return thisValue != StringType && thisValue.IsEntity()&&thisValue!=UtilConstants.ByteArrayType;
}
}
}

View File

@ -317,6 +317,10 @@ namespace SqlSugar
{
return "SqlSugar.ClickHouse.ClickHouse" + name;
}
else if (type == "GBase")
{
return "SqlSugar.GBase.GBase" + name;
}
else if (type == "Custom")
{
return CustomNamespace + "."+CustomDbName + name;

View File

@ -47,7 +47,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqlSugar.ClickHouseCore", "
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ClickHouseTest", "ClickHouseTest\ClickHouseTest.csproj", "{A5249DEC-D1E8-4D95-8C96-534EF98A3E1B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GbaseTest", "GbaseTest\GbaseTest.csproj", "{1D047616-7B42-403F-A54A-C677074CDACF}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GbaseTest", "GbaseTest\GbaseTest.csproj", "{1D047616-7B42-403F-A54A-C677074CDACF}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SqlSugar.GBaseCore", "SqlSugar.GBaseCore\SqlSugar.GBaseCore.csproj", "{73861B80-AC53-441D-A178-C8F3C1FF0FB3}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D6090616-041D-4E87-99E2-737DA91CA47C}"
ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -323,6 +330,18 @@ Global
{1D047616-7B42-403F-A54A-C677074CDACF}.Release|ARM32.Build.0 = Release|Any CPU
{1D047616-7B42-403F-A54A-C677074CDACF}.Release|x86.ActiveCfg = Release|Any CPU
{1D047616-7B42-403F-A54A-C677074CDACF}.Release|x86.Build.0 = Release|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Debug|ARM32.ActiveCfg = Debug|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Debug|ARM32.Build.0 = Debug|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Debug|x86.ActiveCfg = Debug|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Debug|x86.Build.0 = Debug|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|Any CPU.Build.0 = Release|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|ARM32.ActiveCfg = Release|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|ARM32.Build.0 = Release|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|x86.ActiveCfg = Release|Any CPU
{73861B80-AC53-441D-A178-C8F3C1FF0FB3}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -331,6 +350,7 @@ Global
{D22873F3-80E1-4415-9CD6-21B1C7EEA4A0} = {88992AAF-146B-4253-9AD7-493E8F415B57}
{DD0C850D-86E5-4FFF-BFF3-8797EB448B47} = {88992AAF-146B-4253-9AD7-493E8F415B57}
{8C38F3D1-6D72-483C-9DBD-3111D6F5898D} = {88992AAF-146B-4253-9AD7-493E8F415B57}
{73861B80-AC53-441D-A178-C8F3C1FF0FB3} = {88992AAF-146B-4253-9AD7-493E8F415B57}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {230A85B9-54F1-41B1-B1DA-80086581B2B4}