Skip to content

Instantly share code, notes, and snippets.

@trailmax
Created March 28, 2014 02:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trailmax/9823952 to your computer and use it in GitHub Desktop.
Save trailmax/9823952 to your computer and use it in GitHub Desktop.
MigrationDecompression class to support this post: http://tech.trailmax.info/2014/03/inside_of_ef_migrations/
using System;
using System.Data.SqlClient;
using System.IO;
using System.IO.Compression;
using System.Data.Entity.Migrations.Infrastructure;
using System.Xml.Linq;
using MyApplication.Migrations;
using NUnit.Framework;
namespace MyApplication.Tests.Data.Migrations
{
[Ignore("Only for manual execution. Not a test")]
public class MigrationDecompressor
{
[Test]
public void DecompressMigrationEncoding()
{
var migrationClass = (IMigrationMetadata)new MyMigration();
var target = migrationClass.Target;
var xmlDoc = Decompress(Convert.FromBase64String(target));
Console.WriteLine(xmlDoc);
}
[TestCase("MyMigration")]
public void DecompressDatabaseMigration(String migrationName)
{
const string ConnectionString = // connection string to DB with migrations
var sqlToExecute = String.Format("select model from __MigrationHistory where migrationId like '%{0}'", migrationName);
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
var command = new SqlCommand(sqlToExecute, connection);
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
throw new Exception("Now Rows to display. Probably migration name is incorrect");
}
while (reader.Read())
{
var model = (byte[])reader["model"];
var decompressed = Decompress(model);
Console.WriteLine(decompressed);
}
}
}
/// <summary>
/// Stealing decomposer from EF itself:
/// http://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/Migrations/Edm/ModelCompressor.cs
/// </summary>
public virtual XDocument Decompress(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
{
using (var gzipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
{
return XDocument.Load(gzipStream);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment