.Net 数据库更新问题

问题描述 投票:0回答:0

我正在尝试通过学习 Udemy 上的课程来实现电子商务网站。我正在尝试更新我的数据库。我创建了一个名为 ProductCategories 的新表,它允许 ProductsCategories 之间的多对多关系。问题是我的代码生成了表格,并将产品添加到Product 表,但是,它cannot 填充ProductCategories 表。

类别.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace shopapp.entity
{
    public class Category
    {
        public int CategoryId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<ProductCategory> ProductCategories { get; set; }
    }
}

产品.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace shopapp.entity
{
    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; } 
        public double Price { get; set; } 
        public string Description { get; set; } 
        public string ImageUrl { get; set; }
        public bool IsApproved { get; set; }
        public int CategoryId { get; set; }
        public List<ProductCategory> ProductCategories { get; set; }
    }
}

ProductCategory.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace shopapp.entity
{
    public class ProductCategory
    {
        public int CategoryId { get; set; }
        public Category Category { get; set; }
        public int ProductId { get; set; }
        public Product Product { get; set; }
    }
}

DbContext.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using shopapp.entity;

namespace shopapp.data.Concrete.EfCore
{
    public class ShopContext:DbContext
    {
        public DbSet<Product> Products { get; set; }
        public DbSet<Category> Categories { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            // TODO
            // check MySql version
            optionsBuilder.UseMySQL("Server=localhost;port=3306;Database=shopapp2;Uid=root;Pwd=admin;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
                     
            modelBuilder.Entity<ProductCategory>()
            .HasOne(pc => pc.Category)
            .WithMany(pc => pc.ProductCategories)
            .HasForeignKey(pc => pc.ProductId);

            modelBuilder.Entity<ProductCategory>()
            .HasOne(pc => pc.Product)
            .WithMany(pc => pc.ProductCategories)
            .HasForeignKey(pc => pc.CategoryId);
        }
    }   

}

SeedDatabse.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using shopapp.entity;

namespace shopapp.data.Concrete.EfCore
{
    public static class SeedDatabase
    {
        public static void Seed()
        {
            using(var context = new ShopContext())
            {
                Console.WriteLine(context.Database.GetPendingMigrations().Count());
                if (context.Database.GetPendingMigrations().Count() == 0)
                {
                    Console.WriteLine(context.Categories.Count());
                    Console.WriteLine(context.Products.Count());
                    
                    if (context.Categories.Count() == 0)
                    {
                        context.Categories.AddRange(Categories);
                        Console.WriteLine("Categories added!");
                        //Console.WriteLine("Products and ProductCategories added!");
                    }

                    if (context.Products.Count() == 0)
                    {
                        context.Products.AddRange(Products);
                        context.AddRange(ProductCategories); // we do not need to specify Product or category
                    }
                    context.SaveChanges();
                }
            }
            
        }

        private static Category[] Categories = {
            new Category(){ CategoryId=4, Name = "Fashion", Description="Fashion Category"},
            new Category(){ CategoryId=5, Name = "Supermarket", Description="Supermarket Category"},
            new Category(){ CategoryId=6, Name = "Mom and Baby", Description="Mom and Baby Category"}
        };

        private static Product[] Products = {
            new Product(){ProductId=11, Name = "Test Product 1", Price=1000, Description="Test Data", ImageUrl="test.jpg", IsApproved=true},
            new Product(){ProductId=12, Name = "Test Product 2", Price=1200, Description="Test Data", ImageUrl="test.jpg", IsApproved=true},
            new Product(){ProductId=13, Name = "Test Product 3", Price=1400, Description="Test Data", ImageUrl="test.jpg", IsApproved=false}
            
        };

        private static ProductCategory[] ProductCategories = 
        {
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]},
            new ProductCategory(){CategoryId = Categories[0].CategoryId, Category=Categories[0], ProductId = Products[0].ProductId, Product=Products[2]}
        };
    }
}

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using shopapp.business.Abstract;
using shopapp.business.Concrete;
using shopapp.data.Abstract;
using shopapp.data.Concrete.EfCore;

namespace shopapp.webui
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // IProductRepository'yi uygulama çağırıldığı zaman EfCoreProductRepository nesne oluşturulup gönderilecek.
            services.AddScoped<IProductRepository,EfCoreProductRepository>();
            services.AddScoped<IProductService,ProductManager>();
            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // checks if the app is in development process
            // Call your Seed method
            // env is a global variable, you can change this in 
            // /shopapp\\.vscode\\launch.json file
            // by changing 
            /*
            "env": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            */
            // to
            /*"env": {
                "ASPNETCORE_ENVIRONMENT": "Production"
            },*/
            // when you publish your website
            if (env.IsDevelopment())
            {
                SeedDatabase.Seed();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                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.UseEndpoints(endpoints =>
            {

                endpoints.MapControllerRoute(
                    name: "products",
                    pattern: "products/{category?}",
                    defaults: new {controller="Shop", action="list"}
                );

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

我正在使用 .Net 7.0.102.

c# .net entity-framework asp.net-core
© www.soinside.com 2019 - 2024. All rights reserved.