直接复制不需要改任何东西
public class Repository<T> : SimpleClient<T> where T : class, new()
{
public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
{
base.Context = DbScoped.SugarScope;
}
}DbScoped.Sugar 是注入对象,如果还不会注入请看这里学习:https://www.donet5.com/Doc/10/2262
根据不同的实体获取相应的连接对象,当然你也可以封装的更好根据实体特性获取不同的ConfigId
public class Repository<T> : SimpleClient<T> where T : class, new()
{
protected ITenant itenant = null;//多租户事务
public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null
{
var configId = typeof(T).GetCustomAttribute<TenantAttribute>().configId;
//根据特性指定具体使用哪个库
base.Context = DbScoped.SugarScope.GetConnection(configId);
itenant = DbScoped.SugarScope;
}
}
public class UserManager : Repository<UserInfo>
{
//创用仓储方式
public UserInfo Login(string userName, string password)
{
//使用仓储方式 IsAny
return base.GetSingle(it => it.UserName == userName && it.Password == password);
}
//使用db处理复杂对象
public List<Order> GetMapping()
{
var db = base.Context;//使用注入的db对象
var result = db.Queryable<Order>()
.Mapper(it => it.Items, it => it.Items.First().OrderId)
.ToList();
return result;
}
//使用事务
public void TestTran()
{
try
{
itenant.BeginTran();
base.Insert(new UserInfo() { });
var orderDal= base.ChangeRepository<Repository<Order>>();//切换仓储
orderDal.Insert(new Order() { });
itenant.CommitTran();
}
catch (Exception ex)
{
itenant.RollbackTran();
throw ex;
}
}
}实体加上标识区分走哪个库 (SqlSugar 5.0.2.9 支持了自带特性)
[TenantAttribute("1")]
public class C1Table
{
public string Id { get; set; }
}
[TenantAttribute("2")]
public class C2Table
{
public string Id { get; set; }
}
2016 © donet5.comApache Licence 2.0