При запуске было выброшено исключение
р>
Код: Выделить всё
add-migration v1.0.0
Код: Выделить всё
public static IServiceCollection ConfigureDbContextPool(this IServiceCollection services, IConfiguration configuration,IEnumerable? includeDbNames = null,IEnumerable? ignoreDbNames = null)
{
var models = configuration.GetSection("DatabaseConnections").Get();
if (models == null || models.Count == 0)
{
throw new Exception("未配置数据库连接");
}
models = models
.Where(includeDbNames != null, model => includeDbNames!.Contains(model.Name))
.Where(ignoreDbNames != null, model => !ignoreDbNames!.Contains(model.Name))
.ToList();
models.ForEach(model =>
{
services.AddDbContextPool(options =>
{
switch (model.Provider)
{
case DbProviders.NpgSql:
options.UseNpgsql(model.ConnectionString,optionBuiler => optionBuiler.MigrationsAssembly(MigrationAssembly));
break;
default:
break;
}
});
});
return services;
}
Код: Выделить всё
public class SystemDbContext:DbContext
{
public SystemDbContext(DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
DynamicLoadDbSet(modelBuilder);
// 获取所有继承自 IEntityBase 的实体类型
var entityBaseType = typeof(IEntityBase);
var entityTypes = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.IsClass && !t.IsAbstract && entityBaseType.IsAssignableFrom(t));
// 为每个实体类型应用 ConfigurableEntityBase 配置
foreach (var entityType in entityTypes)
{
var method = typeof(ModelBuilder).GetMethods()
.First(m => m.Name == "Entity" && m.IsGenericMethod)
.MakeGenericMethod(entityType);
var entityBuilder = method.Invoke(modelBuilder, null);
// entityType 继承了TDbcontetxtlocator,所以获取泛型参数
var dbContextLocatorType = entityType?.BaseType?.GenericTypeArguments.Where(a=>a.GetInterface(nameof(IDbContextLocator))!=null).FirstOrDefault();
if (entityType == null || dbContextLocatorType == null)
continue;
var configType = typeof(ConfigurableEntityBase).MakeGenericType(entityType, dbContextLocatorType);
var configInstance = Activator.CreateInstance(configType);
var configureMethod = configType.GetMethod("Configure");
configureMethod?.Invoke(configInstance, new[] { entityBuilder });
}
base.OnModelCreating(modelBuilder);
}
private void DynamicLoadDbSet(ModelBuilder modelBuilder)
{
var assembly = Assembly.GetExecutingAssembly();
foreach (Type type in assembly.ExportedTypes)
{
if (type.IsClass && type != typeof(EntityBase) && typeof(EntityBase).IsAssignableFrom(type))
{
var method = modelBuilder.GetType().GetMethods().Where(x => x.Name == "Entity").FirstOrDefault();
if (method != null)
{
method = method.MakeGenericMethod(new Type[] { type });
method.Invoke(modelBuilder, null);
}
}
}
}
}
Код: Выделить всё
var configType = typeof(ConfigurableEntityBase).MakeGenericType(entityType, dbContextLocatorType);
Подробнее здесь: https://stackoverflow.com/questions/790 ... -to-create