Skip to content

Instantly share code, notes, and snippets.

@arman-hpp
Last active May 10, 2016 15:27
Show Gist options
  • Save arman-hpp/51cd8be5657fb4be5f99c6919472e52f to your computer and use it in GitHub Desktop.
Save arman-hpp/51cd8be5657fb4be5f99c6919472e52f to your computer and use it in GitHub Desktop.
DbContextExtensions
public static class DbContextExtensions
{
public static string GetMigrationHistoryModel(this DbContext dbContext)
{
var modelBase64 = dbContext.Database.SqlQuery<string>(@"
DECLARE @binaryContent VARBINARY(MAX);
SELECT @binaryContent = Model FROM [__MigrationHistory];
SELECT CAST('' AS XML).value( 'xs:base64Binary(sql:variable(''@binaryContent''))', 'varchar(max)' ) AS base64Content;"
).FirstOrDefault();
if (modelBase64 == null) return string.Empty;
var bytes = Convert.FromBase64String(modelBase64);
var uncompressed = Decompress(bytes);
return Encoding.UTF8.GetString(uncompressed);
}
private static byte[] Decompress(byte[] gzip)
{
using (var stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
const int size = 4096;
var buffer = new byte[size];
using (var memory = new MemoryStream())
{
int count;
do
{
count = stream.Read(buffer, 0, size);
if (count > 0)
{
memory.Write(buffer, 0, count);
}
}
while (count > 0);
return memory.ToArray();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment