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

发布于:2025-04-21 ⋅ 阅读:(13) ⋅ 点赞:(0)

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


网站公告

今日签到

点亮在社区的每一天
去签到