.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、恢复数据也是一样,读取文件,序列化插入表中

相关推荐
时光追逐者2 天前
C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
c#·.net·.netcore·.net core
切糕师学AI2 天前
.net core web程序如何设置redis预热?
redis·.netcore
csdn_aspnet3 天前
ASP.NET Core 中的多租户 SaaS 应用程序
.netcore·saas
时光追逐者8 天前
C#/.NET/.NET Core技术前沿周刊 | 第 49 期(2025年8.1-8.10)
c#·.net·.netcore
切糕师学AI8 天前
在 .NET Core 5.0 中启用 Gzip 压缩 Response
.netcore
周杰伦fans10 天前
.NET Core MVC中CSHTML
mvc·.netcore
爱吃香蕉的阿豪16 天前
乐思 AI 智能识别平台(基于 YOLO,.NET+Vue3 开发)开源指南
人工智能·yolo·开源·aigc·.netcore
时光追逐者17 天前
C#/.NET/.NET Core优秀项目和框架2025年7月简报
c#·.net·.netcore
步、步、为营22 天前
.NET Core 3.1 升级到 .NET 8
microsoft·.net·.netcore
时光追逐者23 天前
C#/.NET/.NET Core技术前沿周刊 | 第 48 期(2025年7.21-7.27)
c#·.net·.netcore·.net core