.Net Core Seed Database from Json Files

Viewed 1606

I've been searching ways to seed data on a .Net Core 3.1 MVC app. I've found many samples, starting from the documentation. What I haven't found was good, real-life full-examples using (Json/XML) file. The closest one I found doesn't show how to properly get a (Json/XML) file's location no matter the platform used. I haven't been able to successfully integrate DI solutions found on other stack overflow questions makes me think it's not possible. Hoping someone can help.

Thanks!

1 Answers

The closest one I found doesn't show how to properly get a (Json/XML) file's location no matter the platform used.

If your json file exists in the physical disks,you just use the original physical location:

using (StreamReader r = new StreamReader(@"C:\xxx\xxx\test.json"))

If your json file exists in the project and in the root project,use the following location:

using (StreamReader r = new StreamReader(@"test.json"))

If it exists in the folders in the project,you could use the location like below:

using (StreamReader r = new StreamReader(@"wwwroot/test.json"))

And another thing you need to know,althogh you have multiple models with relationships,be sure the json should contain only one model's data.

Here is a example code:

1.Model:

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int UserId { get; set; }
    public List<User> User { get; set; }
}
public class User
{
    public int Id { get; set; }
    public int Age { get; set; }
}

2.DbContext:

public class YourDbContext : DbContext
{
    public YourDbContext(DbContextOptions<YourDbContext> options)
        : base(options)
    {
    }

    public DbSet<Test> Test { get; set; }
    public DbSet<User> User { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Test>().HasData(SeedTestData());
    }
    public List<Test> SeedTestData()
    {
        var tests = new List<Test>();
        using (StreamReader r = new StreamReader(@"test.json"))
        {
            string json = r.ReadToEnd();
            tests = JsonConvert.DeserializeObject<List<Test>>(json);
        }
        return tests;
    }
    public List<User> SeedUserData()
    {
        var users = new List<User>();
        using (StreamReader r = new StreamReader(@"test2.json"))
        {
            string json = r.ReadToEnd();
            users = JsonConvert.DeserializeObject<List<User>>(json);
        }
        return users;
    }
}

3.Run following command in Package Manager Console:

>PM Add-Migration init
>PM Update-Database

test.json:

[
  {
    "id": 1,
    "name": "aa"
  },
  {
    "id": 2,
    "name": "bb"
  },
  {
    "id": 3,
    "name": "cc"
  }
]

test2.json:

[
  {
    "id": 1,
    "age": 34
  },
  {
    "id": 2,
    "age": 21
  }
]
Related