using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
IEnumerable<T> ReadData<T>(string fileName)
{
var result = new List<T>();
string jsonText = File.ReadAllText(fileName);
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
result = JsonSerializer.Deserialize<List<T>>(jsonText, options);
return result;
}
Code to Write to Database
Get the data from the JSON files
var courses = app.ReadData<Course>("courses.json");
var terms = app.ReadData<Term>("terms.json");
Write the data to the database (only if tables are empty)
using (var context = new Data.SchoolCatalogContext())
{
if(!context.Courses.Any())
context.Courses.AddRange(courses);
if(!context.Terms.Any())
context.Terms.AddRange(terms);
context.SaveChanges();
}
Code to Read from Database
Read and display database contents
using (var context = new Data.SchoolCatalogContext())
{
foreach(var item in context.Courses)
Console.WriteLine(item);
foreach(var item in context.Terms)
Console.WriteLine(item);
}