I am new to programming with asp.net core mvc. We are required to make a database and seed data from json file. Unfortunately I cannot seed the data from my json file and I can see that the Db is created with tables but no data in them. I am confused with older version where people use startup.cs and I dont know if my project need that or not. I will paste my project and i hope i get some solutions for it. Id appreciate any help. thanks
this is my program.cs
using Cenimas.Data;
using Cenimas.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
namespace Cenimas
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<CenimasContext>(options => options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllersWithViews()
.AddRazorRuntimeCompilation();
builder.Services.AddRazorPages();
builder.Services.AddTransient<IMailServices, NullMailServices>();
builder.Services.AddTransient<Seeder>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
else
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//app.MapRazorPages();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
if (args.Length > 0 && args[0].ToLower() == "/seed")
{
SeedData(app);
}
app.Run();
void SeedData(IHost app)
{
var scopedFactory = app.Services.GetService<IServiceScopeFactory>();
using (var scope = scopedFactory.CreateScope())
{
var seeder = scope.ServiceProvider.GetService<Seeder>();
seeder.Seed();
}
}
}
}
}
and this is my Seeder.cs
using Cenimas.Data.Entities;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
namespace Cenimas.Data
{
public class Seeder
{
//private readonly CenimasContext context;
//public Seeder(CenimasContext context)
//{
// this.context = context;
//}
//public void Seed()
//{
//using (var contex = new CenimasContext(
// ServiceProvider.GetRequiredService.DbContextOption<CenimasContext>()))
//{
//}
//if(!context.Products.Any())
//{
// //var filePath = Path.Combine(hosting.ContentRootPath, "Data/art.json");
// //var json = File.ReadAllText(filePath);
// //var products = JsonSerializer.Deserialize<IEnumerable<Product>>(json);
// var order = new List<OrderItem>()
// {
// new OrderItem()
// {
// Product = products.First(),
// Quantity = 5,
// UnitPrice = products.First().Price
// }
// };
// context.Products.AddRange((IEnumerable<Product>)order);
// context.SaveChanges();
//}
//}
private readonly CenimasContext ctx;
private readonly IWebHostEnvironment hosting;
public Seeder(CenimasContext ctx, IWebHostEnvironment hosting)
{
this.ctx = ctx;
this.hosting = hosting;
}
public void Seed()
{
ctx.Database.EnsureCreated(); //look at Db and see if its created
if (!ctx.Movies.Any()) //if DB is not created
{
//create a path to our data that will be seeded in our database (in vid 01,04,15)
var filePath = Path.Combine(hosting.ContentRootPath, "Data/MoviesList.json");
var json = File.ReadAllText(filePath);
var movies = JsonSerializer.Deserialize<IEnumerable<Movies>>(json);
//ctx.Movies.AddRange(movies);
//var order = ctx.Orders.Where(o => o.Id == 1).FirstOrDefault(); //crreating loop
//if (order != null)
//{
// order.Items = new List<OrderItem>()
// {
// new OrderItem()
// {
// Product = products.First(),
// Quantity = 5,
// UnitPrice = products.First().Price
// }
// };
//}
//ctx.Orders.Add(order);
ctx.SaveChanges();
}
//}
}
}
}
CenimaContext.se
using Cenimas.Data.Entities;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace Cenimas.Data
{
public class CenimasContext : DbContext
{
//private readonly IConfiguration config;
private readonly IConfiguration appsettings;
//public CenimasContext(IConfiguration config)
//{
// this.config = config;
//}
public CenimasContext(IConfiguration appsettings)
{
this.appsettings = appsettings;
}
public DbSet<Movies> Movies { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) // to connect our database
{
//var config = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("config").Build();
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(appsettings.GetConnectionString("DefaultConnection"));
}
//protected override void OnModelCreating(ModelBuilder modelBuilder) // to show our data in tables
//{
// base.OnModelCreating(modelBuilder);
// modelBuilder.Entity<Order>()
// .HasData(new Order() // then we create migration to it (SeedData)
// {
// Id = 1,
// OrderDate = DateTime.Now,
// OrderNumber = "12345"
// });
//}
}
}
Movies.cs
namespace Cenimas.Data.Entities
{
public class Movies
{
public int Id { get; set; }
public string Title { get; set; }
public string Year { get; set; }
public string Runtime { get; set; }
public string Genre { get; set; }
public string Awards { get; set; }
}
}
and a sample of json file MoviesList.json
[
{
"Id": 1,
"Title": "Avatar",
"Year": "2009",
"Runtime": "162 min",
"Genre": "Action, Adventure, Fantasy",
"Language": "English, Spanish",
"Awards": "Won 3 Oscars. Another 80 wins & 121 nominations."
},
{
"Id": 2,
"Title": "I Am Legend",
"Year": "2007",
"Released": "14 Dec 2007",
"Genre": "Drama, Horror, Sci-Fi",
"Awards": "9 wins & 21 nominations."
},
{
"Id": 3,
"Title": "300",
"Year": "2006",
"Released": "09 Mar 2007",
"Genre": "Action, Drama, Fantasy",
"Awards": "16 wins & 42 nominations."
}
]