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

相关推荐
csdn_aspnet3 天前
MongoDB C# .NetCore 驱动程序 序列化忽略属性
mongodb·c#·.netcore
Tiger_shl4 天前
【.Net技术栈梳理】08-控制反转(IoC)与依赖注入(DI)
开发语言·.net·.netcore
Tiger_shl4 天前
【.Net技术栈梳理】10-.NET Core 程序的执行
开发语言·.net·.netcore
MoFe15 天前
【.net core】【watercloud】登陆后跳转至指定页面,显示在系统框架页内
.netcore
周杰伦fans5 天前
.net core webapi/mvc阿里云服务器部署 - 错误解决
阿里云·mvc·.netcore
驾驭人生7 天前
Asp .Net Core 系列:Asp .Net Core 集成 Hangfire+MySQL
数据库·mysql·.netcore
时光追逐者7 天前
C#/.NET/.NET Core技术前沿周刊 | 第 53 期(2025年9.1-9.7)
c#·.net·.netcore
somethingGoWay8 天前
wpf .netcore 导出docx文件
wpf·.netcore
somethingGoWay9 天前
wpf .netcore 导出pdf文件
pdf·wpf·.netcore
切糕师学AI9 天前
如何建立针对 .NET Core web 程序的线程池的长期监控
java·前端·.netcore