.net core 使用 freesql 备份结构和数据

1、获取表结构

复制代码
//获取表结构,无分库
List<DbTableInfo> dbTableInfos =
    _freeSql.DbFirst.GetTablesByDatabase(_freeSql.DbFirst.GetDatabases()[0]);

2、序列化表结构,序列化时Table字段会循环引用,需要排除掉

复制代码
//备份表结构
dbTableInfos
    .AsParallel()
    .WithDegreeOfParallelism(_backupConfig.backupThread)
    .ForAll(_ =>
{
    //目录名称就是表名
    string tempPath = Path.Combine(filePathName, _.Name);
    //文件
    string tempFilePath = Path.Combine(tempPath, _.Name);

    _iLogger.Info($"备份表:{_.Name},备份文件路径:{tempPath}");

    if (!Directory.Exists(tempPath))
    {
        Directory.CreateDirectory(tempPath);
    }

    //表结构
    string tableStructure = JsonHelperEx.SerializeSettingsEx(_, new Newtonsoft.Json.JsonSerializerSettings()
    {
        ContractResolver = new IgnorePropertiesContractResolver(new[] { "Table" })
    });

    //写入文件
    File.WriteAllText(tempFilePath, tableStructure);
    _iLogger.Info($"备份表结构:{_.Name},完成");
});

注:排除的代码

复制代码
/// <summary>
/// 序列化时过滤某个字段
/// </summary>
public class IgnorePropertiesContractResolver : DefaultContractResolver
{
    private readonly HashSet<string> _ignoreProps;

    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="propNamesToIgnore"></param>
    public IgnorePropertiesContractResolver(IEnumerable<string> propNamesToIgnore)
    {
        _ignoreProps = new HashSet<string>(propNamesToIgnore);
    }

    /// <summary>
    /// 创建映射
    /// </summary>
    /// <param name="member"></param>
    /// <param name="memberSerialization"></param>
    /// <returns></returns>
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);
        if (_ignoreProps.Contains(property.PropertyName))
        {
            property.ShouldSerialize = _ => false;
        }
        return property;
    }
}

3、备份数据

复制代码
//数据
List<object> list = _freeSql
    .Select<object>()
    .AsTable((_, _) => _.Name)
    .Page(i, pageNum)
    .ToList();
_iLogger.Info($"第 {i} 页数据:{list.Count}");
//处理数据
File.WriteAllText(tempDataFilePath, JsonConvert.SerializeObject(list, Formatting.Indented));

4、恢复表结构,将文件加载后反序列化恢复数据对象DbTableInfo

复制代码
DbTableInfo dbTableInfo = JsonConvert.DeserializeObject<DbTableInfo>(json);

//处理注解
List<Attribute> attributes = new List<Attribute>();

//表注解
attributes.Add(new TableAttribute() { Name = dbTableInfo.Name });
//索引注解
dbTableInfo.Uniques.ForEach(uni =>
{
    attributes.Add(new IndexAttribute(uni.Name, uni.Columns[0].Column.Name.ToLower(), uni.IsUnique));
});

DynamicCompileBuilder dynamicCompile =
            _freeSql
                .CodeFirst
                .DynamicEntity(_.Name, attributes.ToArray());
//列映射
dbTableInfo.Columns.ForEach(col =>
        {
            _iLogger.Info($"备份到字段:{col.Name}");
            dynamicCompile = dynamicCompile
                        .Property(col.Name, typeof(string), new ColumnAttribute
                        {
                            IsIdentity = col.IsIdentity,
                            IsPrimary = col.IsPrimary,
                            IsNullable = col.IsNullable,
                            Position = (short)col.Position,
                            StringLength = col.MaxLength
                        });
        });

//恢复结构
_freeSql.CodeFirst.SyncStructure(dynamicCompile.Build().Type);

5、恢复数据也是一样,读取文件,序列化插入表中

相关推荐
吾门32 分钟前
机器视觉开发教程——C#如何封装海康工业相机SDK调用OpenCV/YOLO/VisionPro/Halcon算法
图像处理·opencv·计算机视觉·c#·.net·.netcore·visual studio
Kookoos1 天前
ABP vNext + EF Core 实战性能调优指南
数据库·后端·c#·.net·.netcore
[email protected]2 天前
ASP.NET Core 中实现 Markdown 渲染中间件
后端·中间件·asp.net·.netcore
吃瓜日常3 天前
ABP项目发布到IIS流程
c#·.netcore
[email protected]5 天前
ASP.NET Core 中间件
后端·中间件·asp.net·.netcore
[email protected]6 天前
ASP.NET Core 请求限速的ActionFilter
后端·asp.net·.netcore
菜鸟分享录6 天前
使用 Semantic Kernel 快速对接国产大模型实战指南(DeepSeek/Qwen/GLM)
microsoft·.netcore·semantic kernel
观无7 天前
Ocelot\Consul\.NetCore的微服务应用案例
.netcore·consul
观无7 天前
Nginx发布Vue(ElementPlus),与.NETCore对接(腾讯云)
vue.js·nginx·.netcore
江沉晚呤时8 天前
深入解析 SqlSugar 与泛型封装:实现通用数据访问层
数据结构·数据库·oracle·排序算法·.netcore