.net数据库操作框架SqlSugar的简单入门(2)

   var res=db.Queryable<Person>().Select(it => new Person()    {                  Id=it.Id.SelectAll(),                  SexName=it.SexId.GetConfigValue<DataDictionary>("sex"),                  ProvinceName = it.ProvinceId.GetConfigValue<DataDictionary>("province"),                  CityName = it.CityId.GetConfigValue<DataDictionary>("city"),    }).ToList();   //也支持支持写在Where或者Orderby 

1.4 简单联表查询也可以配置

db.ConfigQuery.SetTable<Order>(it => it.Id, it => it.Name);//配置Order<br> var list3 = db.Queryable<OrderItem>().Select(it => new OrderItem {         ItemId = it.ItemId.SelectAll(),         OrderName = it.OrderId.GetConfigValue<Order>() //查询的时候直接用 }).ToList();

总结:配置表查询的方式可以大大降低重复联表问题,并且配置好后基本就不要写JOIN了 

2、多租户+仓储+自动分配

SqlSugar多租户是通过ConfigId进行识别连接哪个库,新版本添加了实体配置ConfigId

[TenantAttribute("1")]   public class C1Table   {      public string Id { get; set; }   }     [TenantAttribute("2")]   public class C2Table   {       public string Id { get; set; }   }

下面我们仓储就可以通过实体配置自动识别是连接哪个库

public class Repository<T> : SimpleClient<T> where T : class, new()     {         public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null         {             if (context == null)             {                 var db = new SqlSugarClient(new List<ConnectionConfig> {                                                     new ConnectionConfig()                                                 {                                                     ConfigId="1",                                                     DbType = SqlSugar.DbType.SqlServer,                                                     IsAutoCloseConnection = true,                                                     ConnectionString = Config.ConnectionString                                                 },                                                     new ConnectionConfig()                                                 {                                                     ConfigId="2",                                                     DbType = SqlSugar.DbType.SqlServer,                                                     IsAutoCloseConnection = true,                                                     ConnectionString = Config.ConnectionString2                                                 }                 });                 base.Context = db;                 var configId = typeof(T).GetCustomAttribute<TenantAttribute>().configId;                 db.ChangeDatabase(configId);             }         }           /// <summary>         /// 扩展方法,自带方法不能满足的时候可以添加新方法         /// </summary>         /// <returns></returns>         public List<T> CommQuery(string sql)         {             //base.Context.Queryable<T>().ToList();可以拿到SqlSugarClient 做复杂操作             return base.Context.Queryable<T>().Where(sql).ToList();         }       }

新版本还添加了切换仓储功能

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyggsy.html