using Learun.Cache.Redis;
using Learun.Util;
using Learun.Util.SqlSugar;
using SqlSugar;
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Documents;
namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
public class ProjectSugar //不能是泛型类
{
private static string redisKey = "_ec_project";//不需要后缀
///
/// 按项目取表名
///
/// 实体类Entity
/// 项目ID或Index
///
public static string TableName(string projectIdOrIndex) where T : class, new()
{
//按项目取表名公用方法
string tableName = SqlSugarHelper.Db.EntityMaintenance.GetTableName();
if (int.TryParse(projectIdOrIndex, out int ProjIndex))
{
tableName += "_" + projectIdOrIndex;//免得再去查一下数据库,直接给index的情况下
}
else if (!projectIdOrIndex.IsEmpty())
{
//var project = SqlSugarHelper.Db.Queryable().First(x => x.ProjectId == projectIdOrIndex);
var list = new CacheByRedis().GetRedisOrDBData(redisKey,"", () => SqlSugarHelper.Db.Queryable().ToList());
if (list != null)
{
var project = list.FirstOrDefault(x=>x.ProjectId == projectIdOrIndex);
if (project != null)
{
tableName += "_" + project.ProjectIndex.Value;
}
else
{
throw ExceptionEx.ThrowServiceException(new System.Exception(), "无效的ProjectId");
}
}
}
return tableName;//空就返回原表名
}
public static Type FindEntityTypeByTableName(string tableName)
{
// 假设所有实体类都在这个命名空间或者程序集
var allTypes = Assembly.GetExecutingAssembly().GetTypes();
foreach (var type in allTypes)
{
if (!type.IsClass) continue;
var attr = type.GetCustomAttribute();
if (attr != null && string.Equals(attr.TableName, tableName, StringComparison.OrdinalIgnoreCase))
{
return type;
}
// 或者类名就等于表名(如果没加特性)
if (attr == null && string.Equals(type.Name, tableName, StringComparison.OrdinalIgnoreCase))
{
return type;
}
}
return null; // 没找到
}
}
}