SqlSugar/Src/Asp.Net/SqlServerTest/Demo/DemoH_Tenant.cs

81 lines
3.1 KiB
C#
Raw Normal View History

2021-04-24 17:20:15 +08:00
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
2021-04-25 21:37:50 +08:00
namespace OrmTest
2021-04-24 17:20:15 +08:00
{
public class DemoH_Tenant
{
public static void Init()
{
Console.WriteLine("");
2021-08-28 22:30:33 +08:00
Console.WriteLine("#### DemoH_Tenant Start ####");
2021-04-25 20:47:32 +08:00
new C1Service().Test();
2021-08-28 22:30:33 +08:00
Console.WriteLine("#### DemoH_Tenant End ####");
2021-04-24 17:20:15 +08:00
}
2021-04-25 20:47:32 +08:00
public class C1Service : Repository<C1Table>
{
2021-04-25 21:37:50 +08:00
public void Test()
2021-04-25 20:47:32 +08:00
{
2021-08-07 05:14:04 +08:00
db.BeginTran();
2021-04-25 21:37:50 +08:00
base.GetList(); //调用内部仓储方法
base.ChangeRepository<Repository<C2Table>>().GetList();//调用外部仓储
2021-08-07 05:14:04 +08:00
db.CommitTran();
2021-04-25 21:37:50 +08:00
}
2021-04-25 20:47:32 +08:00
}
2021-04-24 17:20:15 +08:00
public class Repository<T> : SimpleClient<T> where T : class, new()
{
2021-08-07 05:14:04 +08:00
//单例实同db同上下文共享
public static SqlSugarScope db = new SqlSugarScope(new List<ConnectionConfig> {
2021-04-24 17:20:15 +08:00
new ConnectionConfig()
{
2021-04-25 21:37:50 +08:00
ConfigId="1",
2021-04-24 17:20:15 +08:00
DbType = SqlSugar.DbType.SqlServer,
IsAutoCloseConnection = true,
ConnectionString = Config.ConnectionString
},
new ConnectionConfig()
{
ConfigId="2",
DbType = SqlSugar.DbType.SqlServer,
IsAutoCloseConnection = true,
ConnectionString = Config.ConnectionString2
}
});
2021-08-07 05:14:04 +08:00
public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
{
if (context == null)
{
2022-04-09 12:13:13 +08:00
Context = db.GetConnectionWithAttr<T>();
2021-08-07 05:14:04 +08:00
Context.CodeFirst.InitTables<T>();
2021-04-24 17:20:15 +08:00
}
}
/// <summary>
/// 扩展方法,自带方法不能满足的时候可以添加新方法
/// </summary>
/// <returns></returns>
public List<T> CommQuery(string sql)
{
//base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作
return base.Context.Queryable<T>().Where(sql).ToList();
}
}
[TenantAttribute("1")]
2021-04-25 21:37:50 +08:00
public class C1Table
2021-04-24 17:20:15 +08:00
{
2021-04-25 21:37:50 +08:00
public string Id { get; set; }
2021-04-24 17:20:15 +08:00
}
[TenantAttribute("2")]
public class C2Table
{
public string Id { get; set; }
}
}
}