Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
870 views
in Technique[技术] by (71.8m points)

entity framework - Can I get decode an EntityFramework Model from a specified migration?

Apparently IMigrationMetadata.Target encodes the state of the EF model. Can I use this to reconstruct the model for a particular migration?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, it is possible. I was myself curious what exactly those magic resource strings were storing. By digging into the Entity Framework source (see the DbMigrator.GetLastModel() method), I found out that the IMigrationMetadata.Target just stores a base-64 string containing gzipped XML data. To test this, I created a new console application containing a simple code-first model defined as follows:

public class ContactContext : DbContext
{
    public virtual IDbSet<Contact> Contacts { get; set; }
}

public class Contact 
{
    public int Id {get; set;}
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Then I created a migration using the NuGet Package Manager Console:

PM> Enable-Migrations
PM> Add-Migration MyMigration

Next I added the following code to my application's Main() method to decode the value in that string and dump it to the console:

var migration = new MyMigration();
var metadata = (IMigrationMetadata)migration;
var compressedBytes = Convert.FromBase64String(metadata.Target);
var memoryStream = new MemoryStream(compressedBytes);
var gzip = new GZipStream(memoryStream, CompressionMode.Decompress);
var reader = new StreamReader(gzip);
Console.WriteLine(reader.ReadToEnd());

This outputs an EDMX file representing the Entity Data Model associated with my DbContext that created the migration. If I write this output to a file with the .edmx extension, I'm able to open it with Visual Studio and view it in the Entity Designer.

Then if for some reason I wanted to regenerate the DbContext and entity classes that produced the model, I would need only do the following:

  1. Add the .edmx file to a Visual Studio project.
  2. Install the EF 5.x DbContext Generator for C# if I don't already have it.
  3. Add the related T4 templates by selecting Add -> New Item from project node context menu.
  4. Modify the newly added .tt files, replacing $edmxInputFile$ with the name of my .edmx file.
  5. Watch as the two templates magically regenerate my code-first types to their respective .cs files.

Hope that answers your question! :-D


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...