Search code examples
asp.net-core-mvcseedingasp.net-core-6.0

Trouble with Seeding data in ASP.NET Core 6


I am currently having problem while trying to seed my data in ASP.NET Core 6. After running the application, I don't see any data updated in my database. Below is my code for DbInitializer.cs and Program.cs.

This is my DbInitializer.cs file:

using e_commerce.Models;

namespace e_commerce.Data
{
    public class DataSeeder
    {
        private readonly ShopDbContext shopDbContext;

        public DataSeeder(ShopDbContext shopDbContext)
        {
            this.shopDbContext = shopDbContext; 
        }  

        public void Seed()
        {
                if (!shopDbContext.Users.Any())
                {
                    var User_List = new List<User>()
                    {
                        new User()
                        {
                            UserId = 1,
                            FirstName = "David", 
                            LastName = "D",
                            Email = "davidd.com",
                            Password = "1234"
                        },

                        new User()
                        {
                            UserId=2, 
                            FirstName = "Alex",
                            LastName = "S",
                            Email="[email protected]",
                            Password="1234"
                        }
                    };
                    shopDbContext.Users.AddRange(User_List);
                    shopDbContext.SaveChanges();
                }
                //Products
                List<Product_Seller> MacBook_Sellers = new List<Product_Seller>();
                Product_Seller macbook_seller_1 = new Product_Seller();
                macbook_seller_1.SellerID = 1;
                macbook_seller_1.ProductID = 1;
                Product_Seller macbook_seller_2 = new Product_Seller();
                macbook_seller_2.SellerID = 2;
                macbook_seller_2.ProductID = 1;
                MacBook_Sellers.Add(macbook_seller_1);
                MacBook_Sellers.Add(macbook_seller_2);
  // adding elements using add() method
                
                if (!shopDbContext.Products.Any())
                {
                    var Product_list = new List<Product>()
                    {
                        new Product()
                        {
                            ProductID = 1,
                            ProductName = "Macbook Pro 2022",
                            ProductImageUrl = "https://i.ibb.co/7nWnHc7/macbookpro.jpg",
                            ProductPrice = 2000.00,
                            Products_Sellers = MacBook_Sellers
                        },
                        new Product()
                        {
                            ProductID = 2, 
                            ProductName = "Dell XPS",
                            ProductImageUrl = "https://i.ibb.co/KXxJsfM/dellxps.jpg",
                            ProductPrice = 1999.00,
                            SellerID = 2
                        }

                    };
                    shopDbContext.Products.AddRange(Product_list);
                    shopDbContext.SaveChanges();

                }
                //Sellers
                List<Product_Seller> store_1_product = new List<Product_Seller>();
                Product_Seller product1 = new Product_Seller();
                product1.SellerID = 1;
                product1.ProductID = 1;
                Product_Seller product2 = new Product_Seller();
                product2.SellerID = 1;
                product2.ProductID = 2;
                store_1_product.Add(product1);
                store_1_product.Add(product2);

                if (!shopDbContext.Sellers.Any())
                {
                    var Seller_list = new List<Seller>()
                    {
                        new Seller()
                        {
                            SellerId = 1,
                            SellerFirstName = "Da",
                            SellerLastName = "Du",
                            SellerEmail = "[email protected]",
                            SellerPassword = "1234",
                            SellerPhone = 1900,
                            SellerReview = 5,
                            Products_Sellers = store_1_product

                        },

                        new Seller()
                        {
                            SellerId = 2, 
                            SellerFirstName = "Ng",
                            SellerLastName = "Le",
                            SellerEmail = "[email protected]",
                            SellerPassword = "1234",
                            SellerPhone = 1800,
                            SellerReview = 5, 
                            ProductID = 1
                        }
                    } ;
                    shopDbContext.Sellers.AddRange(Seller_list);
                    shopDbContext.SaveChanges();
                }
            }
        }
}

And this is my Program.cs file

using e_commerce.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnectionString");
builder.Services.AddDbContext<ShopDbContext>(options => options.UseSqlServer(connectionString));
builder.Services.AddControllersWithViews();
builder.Services.AddTransient<DataSeeder>();
//can be placed among other "AddScoped" - above: var app = builder.Build();   

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

//seed 

app.Run();
if (args.Length == 1 && args[0].ToLower() == "seeddata")
    SeedData(app);

//Seed Data
void SeedData(IHost app)
{
    var scopedFactory = app.Services.GetService<IServiceScopeFactory>();

    using (var scope = scopedFactory.CreateScope())
    {
        var service = scope.ServiceProvider.GetService<DataSeeder>();
        service.Seed();
    }
}

Thank you for any help.


Solution

  • I do some change based on your code. And I get the data in the database.

    Seller

    public class Seller
        {
            public int SellerId { get; set; }
    
            public string SellerFirstName { get; set; }
    
            public string SellerLastName { get; set; }
    
            public string SellerEmail { get; set; }
    
    
            public string SellerPassword { get; set; }
    
            public int SellerPhone { get; set; }
    
            public int SellerReview { get; set; }
    
            //Relationships
    
            public List<Product_Seller> Products_Sellers { get; set; }
        }
    

    Product

     public class Product
        {
            public int ProductID { get; set; }
            public string ProductName { get; set; }
            public string ProductImageUrl { get; set; }
    
            public double ProductPrice { get; set; }
    
            //Relationships
    
            public List<Product_Seller> Products_Sellers { get; set; }
    
        }
    

    ShopDbContext

    public class ShopDbContext : DbContext
        {
            public ShopDbContext(DbContextOptions<ShopDbContext> options) : base(options)
            {
    
            }
            public DbSet<Seller> Sellers { get; set; }
    
            public DbSet<Product> Products { get; set; }
    
            public DbSet<Product_Seller> Products_Sellers { get; set; }
    
    
            public DbSet<User> Users { get; set; }
    
    
            protected override void OnModelCreating(ModelBuilder builder)
            {
                base.OnModelCreating(builder);
    
                builder.Entity<Product_Seller>().HasKey(i => new { i.ProductID, i.SellerID });
            }
        }
    

    DataSeeder

     public class DataSeeder
        {
            public static void Initialize(IServiceProvider serviceProvider)
            {
                using (var shopDbContext = new ShopDbContext(
                    serviceProvider.GetRequiredService<
                        DbContextOptions<ShopDbContext>>()))
                {
    
                    if (!shopDbContext.Users.Any())
                    {
                        var User_List = new List<User>()
                        {
                            new User()
                            {
    
                                FirstName = "David",
                                LastName = "D",
                                Email = "davidd.com",
                                Password = "1234"
                            },
    
                            new User()
                            {
    
                                FirstName = "Alex",
                                LastName = "S",
                                Email="[email protected]",
                                Password="1234"
                            }
                        };
                        shopDbContext.Users.AddRange(User_List);
                        shopDbContext.SaveChanges();
                    }
    
    
                    if (!shopDbContext.Products.Any() && !shopDbContext.Sellers.Any())
                    {
    
                        var product1 = new Product()
                        {
    
                            ProductName = "Macbook Pro 2022",
                            ProductImageUrl = "https://i.ibb.co/7nWnHc7/macbookpro.jpg",
                            ProductPrice = 2000.00
    
                        };
                        var product2 = new Product()
                        {
    
                            ProductName = "Dell XPS",
                            ProductImageUrl = "https://i.ibb.co/KXxJsfM/dellxps.jpg",
                            ProductPrice = 1999.00
    
                        };
                        var seller1 = new Seller()
                        {
    
                            SellerFirstName = "Da",
                            SellerLastName = "Du",
                            SellerEmail = "[email protected]",
                            SellerPassword = "1234",
                            SellerPhone = 1900,
                            SellerReview = 5
    
    
                        };
    
                        var seller2 = new Seller()
                        {
    
                            SellerFirstName = "Ng",
                            SellerLastName = "Le",
                            SellerEmail = "[email protected]",
                            SellerPassword = "1234",
                            SellerPhone = 1800,
                            SellerReview = 5
    
                        };
    
    
                        var pslist = new List<Product_Seller>()
                {
                    new Product_Seller() { Product = product1, Seller = seller1 },
                    new Product_Seller() { Product = product1, Seller = seller2 },
    
           
                    new Product_Seller() { Product = product2, Seller = seller1 },
    
                };
                        shopDbContext.Products_Sellers.AddRange(pslist);
    
                        shopDbContext.SaveChanges();
    
                    }
                }
            }
        }
    

    Program

    using Microsoft.EntityFrameworkCore;
    using seed3Many.Data;
    
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    builder.Services.AddControllersWithViews();
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnectionString");
    builder.Services.AddDbContext<ShopDbContext>(options => options.UseSqlServer(connectionString));
    var app = builder.Build();
    using (var scope = app.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
    
        DataSeeder.Initialize(services);
    }
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Home/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    
    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    
    app.Run();
    

    Result:

    enter image description here