簡體   English   中英

在 ASP.NET Core 6 中播種數據的問題

[英]Trouble with Seeding data in ASP.NET Core 6

我目前在嘗試在 ASP.NET Core 6 中播種我的數據時遇到問題。運行應用程序后,我的數據庫中沒有看到任何數據更新。 下面是我的DbInitializer.csProgram.cs代碼。

這是我的DbInitializer.cs文件:

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="alexs@gmail.com",
                            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 = "abcd@gmail.com",
                            SellerPassword = "1234",
                            SellerPhone = 1900,
                            SellerReview = 5,
                            Products_Sellers = store_1_product

                        },

                        new Seller()
                        {
                            SellerId = 2, 
                            SellerFirstName = "Ng",
                            SellerLastName = "Le",
                            SellerEmail = "bcdez@gmail.com",
                            SellerPassword = "1234",
                            SellerPhone = 1800,
                            SellerReview = 5, 
                            ProductID = 1
                        }
                    } ;
                    shopDbContext.Sellers.AddRange(Seller_list);
                    shopDbContext.SaveChanges();
                }
            }
        }
}

這是我的Program.cs文件

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();
    }
}

感謝您的任何幫助。

我根據您的代碼做了一些更改。 我得到數據庫中的數據。

賣方

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; }
    }

產品

 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 });
        }
    }

數據播種機

 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="alexs@gmail.com",
                            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 = "abcd@gmail.com",
                        SellerPassword = "1234",
                        SellerPhone = 1900,
                        SellerReview = 5


                    };

                    var seller2 = new Seller()
                    {

                        SellerFirstName = "Ng",
                        SellerLastName = "Le",
                        SellerEmail = "bcdez@gmail.com",
                        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();

                }
            }
        }
    }

程序

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();

結果:

在此處輸入圖像描述

您需要在 app.Run() 和其他需要數據庫中數據的中間件之前調用 SeedData(app)

我在.net 5中嘗試如下(與.net 6有點不同)

創建了一個靜態類來初始化 dbcontext:

public static class DbInitializer
    {
        public static void Initialize(UserDbtestContext context)
        {
            context.Database.EnsureCreated();
            if (context.User.Any())
            {
                return;   // DB has been seeded
            }
            var users = new List<User>()
            {
                new User(){Email="email",FirstName="firstname1",LastName="lastname1",Password="password"},
                new User(){Email="email",FirstName="firstname2",LastName="lastname2",Password="password"},
                new User(){Email="email",FirstName="firstname2",LastName="lastname2",Password="password"}
            };
            foreach (var user in users)
            {
                context.User.Add(user);
            }
            context.SaveChanges();
        }
    }

在.net 5中修改了SeedData方法,你不需要在你的代碼中修改這個方法

 void SeedData(IApplicationBuilder app)
            {
                var scopedFactory = app.ApplicationServices.GetService<IServiceScopeFactory>();
    
                using (var scope = scopedFactory.CreateScope())
                {
                    var dbcontext = scope.ServiceProvider.GetService<UserDbtestContext>();
                    DbInitializer.Initialize(dbcontext);
                }
            }

在其他中間件之前調用 SeedData(app),結果: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM