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

451 lines
17 KiB

6 years ago
using System;
using System.Collections.Generic;
6 years ago
using System.ComponentModel.DataAnnotations;
using System.Data.Linq.Mapping;
6 years ago
using System.Linq;
using System.Text;
6 years ago
using System.Threading.Tasks;
6 years ago
using SqlSugar;
namespace OrmTest
{
6 years ago
public class Demo0_SqlSugarClient
6 years ago
{
public static void Init()
{
6 years ago
SqlSugarClient();//Create db
DbContext();//Optimizing SqlSugarClient usage
SingletonPattern();//Singleten Pattern
3 years ago
//DistributedTransactionExample(); The demo requires three different databases
6 years ago
MasterSlave();//Read-write separation
6 years ago
CustomAttribute();
6 years ago
}
6 years ago
private static void MasterSlave()
{
Console.WriteLine("");
Console.WriteLine("#### MasterSlave Start ####");
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,//Master Connection
DbType = DbType.SqlServer,
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 ####");
}
6 years ago
private static void SqlSugarClient()
{
6 years ago
//Create db
Console.WriteLine("#### SqlSugarClient Start ####");
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
6 years ago
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
6 years ago
}
}
});
6 years ago
//If no exist create datebase
6 years ago
db.DbMaintenance.CreateDatabase();
6 years ago
//Use db query
6 years ago
var dt = db.Ado.GetDataTable("select 1");
6 years ago
//Create tables
6 years ago
db.CodeFirst.InitTables(typeof(OrderItem),typeof(Order));
var id = db.Insertable(new Order() { Name = "order1", CustomId = 1, Price = 0, CreateTime = DateTime.Now }).ExecuteReturnIdentity();
6 years ago
//Insert data
6 years ago
db.Insertable(new OrderItem() { OrderId = id, Price = 0, CreateTime=DateTime.Now }).ExecuteCommand();
6 years ago
Console.WriteLine("#### SqlSugarClient End ####");
6 years ago
6 years ago
}
private static void DbContext()
{
6 years ago
Console.WriteLine("");
Console.WriteLine("#### DbContext Start ####");
6 years ago
var insertObj = new Order { Name = "jack", CreateTime = DateTime.Now };
6 years ago
var InsertObjs = new Order[] { insertObj };
DbContext context = new DbContext();
6 years ago
context.Db.CodeFirst.InitTables<Order, OrderItem,Custom>();//Create Tables
6 years ago
;
6 years ago
var orderDb = context.OrderDb;
//Select
var data1 = orderDb.GetById(1);
var data2 = orderDb.GetList();
6 years ago
var data3 = orderDb.GetList(it => it.Id == 1);
6 years ago
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);
3 years ago
Console.Write(p.TotalCount);
6 years ago
var data6 = orderDb.GetPageList(it => it.Name == "xx", p, it => it.Name, OrderByType.Asc);
3 years ago
Console.Write(p.TotalCount);
6 years ago
List<IConditionalModel> conModels = new List<IConditionalModel>();
conModels.Add(new ConditionalModel() { FieldName = "id", ConditionalType = ConditionalType.Equal, FieldValue = "1" });//id=1
var data7 = orderDb.GetPageList(conModels, p, it => it.Name, OrderByType.Asc);
orderDb.AsQueryable().Where(x => x.Id == 1).ToList();
//Insert
orderDb.Insert(insertObj);
orderDb.InsertRange(InsertObjs);
var id = orderDb.InsertReturnIdentity(insertObj);
orderDb.AsInsertable(insertObj).ExecuteCommand();
//Delete
orderDb.Delete(insertObj);
6 years ago
orderDb.DeleteById(11111);
orderDb.DeleteById(new int[] { 1111, 2222 });
orderDb.Delete(it => it.Id == 1111);
orderDb.AsDeleteable().Where(it => it.Id == 1111).ExecuteCommand();
6 years ago
//Update
6 years ago
orderDb.Update(insertObj);
orderDb.UpdateRange(InsertObjs);
6 years ago
orderDb.Update(it => new Order() { Name = "a", }, it => it.Id == 1);
6 years ago
orderDb.AsUpdateable(insertObj).UpdateColumns(it => new { it.Name }).ExecuteCommand();
//Use Inherit DbContext
OrderDal dal = new OrderDal();
6 years ago
var data = dal.GetById(1);
6 years ago
var list = dal.GetList();
6 years ago
Console.WriteLine("#### DbContext End ####");
6 years ago
}
6 years ago
private static void CustomAttribute()
{
Console.WriteLine("");
Console.WriteLine("#### Custom Attribute Start ####");
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
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;
}
}
}
});
6 years ago
db.CodeFirst.InitTables<AttributeTable>();//Create Table
6 years ago
6 years ago
db.Insertable(new AttributeTable() { Id = Guid.NewGuid().ToString(), Name = "Name" }).ExecuteCommand();
var list = db.Queryable<AttributeTable>().ToList();
6 years ago
Console.WriteLine("#### Custom Attribute End ####");
}
6 years ago
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 ####");
}
3 years ago
static SqlSugarScope singleDb = new SqlSugarScope(
6 years ago
new ConnectionConfig()
{
ConfigId = 1,
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
6 years ago
IsAutoCloseConnection = true,
6 years ago
AopEvents = new AopEvents()
{
OnLogExecuting = (sql, p) => { Console.WriteLine(sql); }
}
});
6 years ago
private static void DistributedTransactionExample()
{
Console.WriteLine("");
Console.WriteLine("#### Distributed TransactionExample Start ####");
SqlSugarClient db = new SqlSugarClient(new List<ConnectionConfig>()
{
6 years ago
new ConnectionConfig(){ ConfigId="1", DbType=DbType.SqlServer, ConnectionString=Config.ConnectionString,InitKeyType=InitKeyType.Attribute,IsAutoCloseConnection=true },
new ConnectionConfig(){ ConfigId="2", DbType=DbType.SqlServer, ConnectionString=Config.ConnectionString2 ,InitKeyType=InitKeyType.Attribute ,IsAutoCloseConnection=true}
6 years ago
});
6 years ago
//use db1
6 years ago
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());
6 years ago
//use db2
db.ChangeDatabase("2");
db.DbMaintenance.CreateDatabase();//Create Database2
6 years ago
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());
6 years ago
// Example 1
Console.WriteLine("Example 1");
6 years ago
try
{
db.BeginTran();
6 years ago
6 years ago
db.ChangeDatabase("1");//use db1
6 years ago
db.Deleteable<Order>().ExecuteCommand();
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
6 years ago
db.ChangeDatabase("2");//use db2
6 years ago
db.Deleteable<Order>().ExecuteCommand();
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
throw new Exception();
db.CommitTran();
6 years ago
}
catch
{
db.RollbackTran();
6 years ago
Console.WriteLine("---Roll back");
6 years ago
db.ChangeDatabase("1");//use db1
6 years ago
Console.WriteLine(db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
6 years ago
db.ChangeDatabase("2");//use db2
6 years ago
Console.WriteLine(db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
}
6 years ago
// Example 2
Console.WriteLine("Example 2");
3 years ago
var result = db.UseTran(() =>
6 years ago
{
6 years ago
db.ChangeDatabase("1");//use db1
6 years ago
db.Deleteable<Order>().ExecuteCommand();
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
6 years ago
db.ChangeDatabase("2");//use db2
6 years ago
db.Deleteable<Order>().ExecuteCommand();
Console.WriteLine("---Delete all " + db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
throw new Exception("");
});
3 years ago
if (result.IsSuccess == false)
{
6 years ago
Console.WriteLine("---Roll back");
6 years ago
db.ChangeDatabase("1");//use db1
6 years ago
Console.WriteLine(db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
6 years ago
db.ChangeDatabase("2");//use db2
6 years ago
Console.WriteLine(db.CurrentConnectionConfig.DbType);
Console.WriteLine(db.Queryable<Order>().Count());
}
// Example 3
Console.WriteLine("Example 3");
3 years ago
Task<DbResult<bool>> result2 = AsyncTranDemo(db);
6 years ago
result2.Wait();
3 years ago
3 years ago
// Example 4
Console.WriteLine("Example 4");
var mysqldb = db.GetConnection("1");//获取ConfigId为1的数据库对象
var sqlServerdb = db.GetConnection("2");//获取默认对象
Console.WriteLine(mysqldb.Queryable<Order>().Count());
Console.WriteLine(sqlServerdb.Queryable<Order>().Count());
try
{
db.BeginTran();
sqlServerdb.Deleteable<Order>().ExecuteCommand();
mysqldb.Deleteable<Order>().ExecuteCommand();
Console.WriteLine(mysqldb.Queryable<Order>().Count());
Console.WriteLine(sqlServerdb.Queryable<Order>().Count());
throw new Exception("");
db.CommitTran();
}
catch (Exception)
{
db.RollbackTran();//数据回滚
Console.WriteLine(mysqldb.Queryable<Order>().Count());
Console.WriteLine(sqlServerdb.Queryable<Order>().Count());
}
6 years ago
Console.WriteLine("#### Distributed TransactionExample End ####");
6 years ago
}
3 years ago
/// <summary>
///Async tran demo
/// </summary>
/// <param name="db"></param>
/// <returns></returns>
private static async Task<DbResult<bool>> AsyncTranDemo(SqlSugarClient db)
{
//need await all
var result2 =await db.UseTranAsync(async () =>
{
//need await all
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("");
});
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());
return result2;
}
6 years ago
}
6 years ago
6 years ago
/// <summary>
/// DbContext Example 1
/// </summary>
6 years ago
public class DbContext
{
public SqlSugarClient Db;
public DbContext()
{
Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = Config.ConnectionString,
DbType = DbType.SqlServer,
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);
}
6 years ago
public class OrderDal : DbContext<Order>
{
6 years ago
6 years ago
}
/// <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.SqlServer,
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);
}
}
6 years ago
}