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

相关推荐
神仙别闹21 小时前
基于 .Net Core+MySQL开发(WinForm)翻译平台
数据库·mysql·.netcore
孤的心了不冷1 天前
【后端】.NET Core API框架搭建(9) --配置使用Log4Net日志
后端·.netcore
孤的心了不冷2 天前
【后端】配置SqlSugar ORM框架并添加仓储
mysql·sqlserver·.netcore
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 46 期(2025年7.7-7.13)
c#·.net·.netcore
王柏龙3 天前
aspnetcore Mvc配置选项中的ModelMetadataDetailsProviders
mvc·.netcore
江沉晚呤时4 天前
在 C# 中调用 Python 脚本:实现跨语言功能集成
python·microsoft·c#·.net·.netcore·.net core
喵叔哟5 天前
3. 【Blazor全栈开发实战指南】--Blazor是什么?为什么选择Blazor?
c#·.netcore
deriva14 天前
.netcore+ef+redis+rabbitmq+dotcap先同步后异步再同步的方法,亲测有效
redis·rabbitmq·.netcore
棉晗榜1 个月前
C# .net core添加单元测试项目,依赖注入接口测试
单元测试·c#·.netcore
时光追逐者1 个月前
.NET初级软件工程师面试经验分享
经验分享·面试·职场和发展·c#·.net·.netcore