Skip to content

Seed Entity Framework Code First With JSON Using C# Dynamic

Updated: at 11:18 PM

If you just want the short version, go to the this GitHub Repository and you’ll find a very simple project that I’ll explain in more detail here.

https://github.com/pkellner/EntityFrameworkSeedFromJSON

Below are the steps necessary to achieve converting JSON into Entity Framework Seeded data.

Copy the JSON file into your Visual Studio project and make the build action (file property in VS) Embedded Resource.

image

Next, find out the name of the embedded resource. If you just don’t know it or don’t want to spend time disassembling the project you can use the GetManifestResourceNames() method as shown below.  I find that is quicker and I don’t typically have those tools loaded when I need or want then.

image

Once we have the manifest name, we can get the json file as a string and then feed that through NewtonSoft.JSON.  Then, using dynamic data we simply do the expected “Seed” with Entity Framework.  Below is the code (as well as in the GitHub Rep).

//public class MultiTenantContextInitializer : DropCreateDatabaseAlways
public class MultiTenantContextInitializer : DropCreateDatabaseAlways
{
//https://connect.microsoft.com/VisualStudio/feedback/details/1934385
// DropCreateDatabaseAlways  CreateDatabaseIfNotExists

protected override void Seed(DbLocalContext context)
{
    GetSpeakers(context);
    context.SaveChanges();
}

private void GetSpeakers(DbLocalContext context)
{
    var speakerJsonAll = 
        GetEmbeddedResourceAsString("EntityFrameworkSeedFromJSON.speaker.json");

    JArray jsonValSpeakers = JArray.Parse(speakerJsonAll) as JArray;
    dynamic speakersData = jsonValSpeakers;
    foreach (dynamic speaker in speakersData)
    {
        context.Speakers.Add(new Speaker
        {
            PictureId = speaker.id,
            FirstName = speaker.firstName,
            LastName = speaker.lastName,
            AllowHtml = speaker.allowHtml,
            Bio = speaker.bio,
            WebSite = speaker.webSite
        });

    }
}

   
private string GetEmbeddedResourceAsString(string resourceName)
{
    var assembly = Assembly.GetExecutingAssembly();

    //var names = assembly.GetManifestResourceNames();

    string result;
    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    using (StreamReader reader = new StreamReader(stream))
    {
        result = reader.ReadToEnd();
    }
    return result;
}

}


HTH's