第25章 通过EntityFrameworkCore中间件验证数据库存在
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using System;
using System.Linq;
using System.Reflection;
namespace MyAppNamespace
{
public static class DatabaseExistenceValidator
{
public static bool ValidateDatabaseExists<TContext>(string connectionString) where TContext : DbContext
{
var optionsBuilder = new DbContextOptionsBuilder<TContext>();
optionsBuilder.UseSqlServer(connectionString);
using (var context = (TContext)Activator.CreateInstance(typeof(TContext), optionsBuilder.Options))
{
var types = Assembly.GetAssembly(typeof(TContext)).GetTypes()
.Where(t => !t.IsAbstract && typeof(ModelBuilder).IsAssignableFrom(t)).ToArray();
foreach (var type in types)
{
var modelBuilder = (ModelBuilder)Activator.CreateInstance(type);
modelBuilder.ApplyConfigurations(type);
var entityTypes = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(m => m.Name.StartsWith("Entity") && m.GetParameters().Length == 0)
.Select(m => m.ReturnType.GetGenericArguments().FirstOrDefault())
.Where(t => t != null);
foreach (var entityType in entityTypes)
{
var entityTypeName = entityType.Name;
var tableName = context.Model.FindEntityType(entityType).GetTableName();
var query = $@"
SELECT 1
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_NAME = N'{tableName}'";
var result = context.Database.ExecuteSqlRaw(query).ToString();
if (result == "1")
{
return true;
}
}
}
}
return false;
}
}
}
这段代码使用了Entity Framework Core的ExecuteSqlRaw
方法来执行原始SQL查询,从而检查数据库中是否存在特定的表。它通过反射查找应用于DbContext的所有ModelBuilder类型,并尝试查找每个类型中定义的实体类型对应的表名。如果找到匹配的表,它会返回true,表明数据库存在。这个方法可以作为在应用程序启动时验证数据库是否准备就绪的一个工具。
评论已关闭