1

情况:我做了一个应用程序更新程序。问题是更新后的应用程序使用的数据库可能不同。

我已经搜索了一个 .dll,它可以制作备份转储并为不同的数据库类型轻松恢复该转储。但遗憾的是没有可用的。

我的第一个想法是为每个 DatabaseType 制作一个用例,并使用 config.txt 文件指定的正确用例。但我的老板不喜欢这种解决方案。因此,我尝试查看是否可以 NHibernate(也用于发送更新文件)来进行数据库备份。可悲的是,虽然这是可能的,但它是不可行的。因为这会产生过多的开销。我还查看了 Rhino.ETL,但遗憾的是没有足够的文档供我使用。

所以我想问一下是否有人知道其他可能有用的方法。还是我辞职是为了违背我老板的意愿并使用每个用例的方法?

4

2 回答 2

3

我使用 NHibernate 进行备份和恢复。导出和导入中实体的顺序很重要

ExportData(config, config.BuildSessionFactory(), dataFile, config.ClassMappings.Select(m => m.EntityName));

public void ExportData(Configuration config, ISessionFactory factory, string dataFile, IEnumerable<string> entitiesToExport)
{
    File.Delete(dataFile);
    using (var zip = new ZipFile(dataFile) { CompressionMethod = CompressionMethod.Deflate, CompressionLevel = CompressionLevel.BestCompression })
    using (var session = factory.OpenStatelessSession())
    using (var tx = session.BeginTransaction())
    {
        foreach (var name in entitiesToExport)
        {
            // copy for closure
            var entityName = name;
            zip.AddEntry(entityName + ".csv", (tablename, outstream) =>
            {
                using (var writer = new StreamWriter(outstream))
                {
                    // mapping der Klasse
                    var entityMap = config.GetClassMapping(entityName);
                    // only properties, no Collections (toMany)
                    var properties = entityMap.PropertyClosureIterator.Where(prop => prop.ColumnSpan > 0).ToArray();

                    // write csv(tsv) header
                    writer.WriteLine(string.Join(SEPERATOR, ToPropertyNames(properties)));

                    var classMetaData = factory.GetClassMetadata(entityName);

                    const int pagesize = 10000;
                    int page = 0;
                    IList<object> objects;
                    do
                    {
                        objects = session.CreateCriteria(entityName)
                            .SetFirstResult(page * pagesize)
                            .SetMaxResults(pagesize)
                            .AddOrder(Order.Asc(Projections.Id()))
                            .List<object>();

                        foreach (var obj in objects)
                        {
                            // get property values as string
                            var values = ToPropertyValues(factory, classMetaData, properties, string.Empty, obj).Select(Serialize);

                            writer.WriteLine(string.Join(SEPERATOR, values));
                        }

                        page++;
                    } while (objects.Count > 0);
                }
            });
        }
        zip.Save(dataFile);
    }
}

并导入

public void ImportData(NHCfg.Configuration config, ISessionFactory factory, string dataFile)
{
    using (var zip = new ZipFile(dataFile))
    using (var session = factory.OpenSession())
    using (var tx = session.BeginTransaction())
    {
        var filesAndMaps = from file in zip.EntryFileNames
                           join map in config.ClassMappings on Path.GetFileNameWithoutExtension(file) equals map.EntityName
                           select new { Filename = file, Entitymap = map };

        foreach (var fileAndMap in filesAndMaps)
        {
            using (Stream stream = zip[fileAndMap.Filename].OpenReader())
            using (StreamReader reader = new StreamReader(stream))
            {
                // mapping der Klasse
                var classMetadata = factory.GetClassMetadata(fileAndMap.Entitymap.EntityName);

                var propertyNames = reader.ReadLine().Split(SEPERATOR[0]).Select(str => str.EndsWith("_Id") ? str.Remove(str.Length - "_Id".Length) : str).ToArray();

                // propertyNamen(/pfade) und typen aus dem mapping holen
                List<string> names = new List<string>();
                List<IType> itypes = new List<IType>();

                names.AddRange(classMetadata.PropertyNames);
                itypes.AddRange(classMetadata.PropertyTypes);
                for (int index = names.Count - 1; index >= 0; index--)
                {
                    var propertyType = itypes[index];
                    if (propertyType.IsComponentType)
                    {
                        var basename = names[index];
                        var componentType = (ComponentType)propertyType;
                        names.RemoveAt(index);
                        names.InsertRange(index, componentType.PropertyNames.Select(name => basename + "." + name));
                        itypes.RemoveAt(index);
                        itypes.InsertRange(index, componentType.Subtypes);
                        index += componentType.Subtypes.Length;
                    }
                    else if (propertyType.IsEntityType)
                    {
                        itypes[index] = factory.GetClassMetadata(((EntityType)propertyType).GetAssociatedEntityName()).IdentifierType;
                    }
                }

                // mit den namen aus der csv abgleichen um den index im array der namen und typen zu bestimmen
                int[] indices = new int[propertyNames.Length];
                for (int i = 0; i < indices.Length; i++)
                {
                    indices[i] = names.IndexOf(propertyNames[i]);
                }

                object[] deserialisedValues = new object[itypes.Count];
                object[] objectValues = new object[classMetadata.PropertyTypes.Length];

                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] serialisedValues = line.Split(SEPERATOR[0]);

                    // Werte deserialisieren
                    for (int i = 0; i < serialisedValues.Length; i++)
                    {
                        // nur deserialisieren wenn es das property überhaupt noch gibt
                        if (indices[i] >= 0)
                            deserialisedValues[indices[i]] = Deserialize(serialisedValues[i], itypes[indices[i]].ReturnedClass);
                    }

                    int offset = 0;
                    for (int i = 0; i < objectValues.Length; i++)
                    {
                        var propertyType = classMetadata.PropertyTypes[i];
                        if (propertyType.IsComponentType)
                        {
                            objectValues[i] = ToComponentObject(deserialisedValues, ref offset, (ComponentType)propertyType, session);
                        }
                        else
                        {
                            objectValues[i] = (propertyType.IsEntityType && deserialisedValues[offset] != null) ?
                                session.Load(((ManyToOneType)propertyType).GetAssociatedEntityName(), deserialisedValues[offset]) :
                                deserialisedValues[offset];

                            offset++;
                        }
                    }
                    object entity = classMetadata.Instantiate(null, EntityMode.Poco);

                    classMetadata.SetPropertyValues(entity, objectValues, EntityMode.Poco);

                    session.Save(entity);
                }
            }
        }
        tx.Commit();
    }
}

不存在的功能是供读者练习的

于 2012-09-14T08:43:59.707 回答
0

很好的答案 Firo,可以把方法“ToPropertyNames”、“ToPropertyValues”和“ToComponentObject”的代码吗?

我补充说要使用它,需要库DotNetZip

于 2015-01-09T00:15:32.317 回答