Я получаю исключение: «Ссылка на объект не соответствует экземпляру объекта». Не понимаю, почему. Что не так с моими связями между таблицами? Я хотел установить связь между таблицами «Страна» и «Компания» по принципу «один-ко-многим», чтобы избежать дублирования стран в таблице «Компания» (это то, как таблица выглядела раньше - Изображение 3. Я хочу создать 3 стол.

Информация об исключении: Image1

Информация2: Image2

Таблица перед: Image3

Исключение происходит в таблицах: «Товар» - «Компания» - «Страна». База данных семян:

using E_Store2021.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace E_Store2021.Data
{
    public static class ApplicationDbContextSeed
    {
        public static async Task SeedAsync(ApplicationDbContext _context, ILoggerFactory loggerFactory)
        {
            try
            {
                _context.Database.EnsureCreated();

                await SeedCategoriesAsync(_context);

                await SeedSubCategories(_context);

                await SeedCountry(_context);

                await SeedCompany(_context);

                await SeedProduct(_context);

            }
            catch(Exception ex)
            {
                var log = loggerFactory.CreateLogger<ApplicationDbContext>();
                log.LogError(ex.Message);
            }
        }
        private static async Task SeedCategoriesAsync(ApplicationDbContext _context)
        {
            if (_context.Categories.Any()) return;
            var categories = new List<Category>()
            {
                new Category
                {
                    Description = "Some category",
                    CategoryName = "Electronics",
                    ImagePath = "category_1.webp"
                },
                new Category
                {
                    Description = "Some category",
                    CategoryName = "Computers",
                    ImagePath = "category_2.webp"
                },
                new Category
                {
                    Description = "Some category",
                    CategoryName = "Music",
                    ImagePath = "category_3.webp"
                },
                new Category
                {
                    Description = "Some category",
                    CategoryName = "Software",
                    ImagePath = "category_4.webp"
                },
                new Category
                {
                    Description = "Some category",
                    CategoryName = "Arts",
                    ImagePath = "category_5.webp"
                },
                new Category
                {
                    Description = "Some category",
                    CategoryName = "Games",
                    ImagePath = "category_6.webp"
                },
            };
            _context.Categories.AddRange(categories);
            await _context.SaveChangesAsync();
        }

        private static async Task SeedSubCategories(ApplicationDbContext _context)
        {
            if (_context.SubCategories.Any()) return;
            var categories = await _context.Categories.ToListAsync();
            var subCategories = new List<SubCategory>
            {
                new SubCategory
                {
                    CategoryID =  categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                    SubCategoryName = "Camera",
                    Description = "Some"
                },
                new SubCategory
                {
                    CategoryID =  categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                    SubCategoryName = "Phones",
                    Description = "Some"
                },
                new SubCategory
                {
                    CategoryID =  categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                    SubCategoryName = "Headphones",
                    Description = "Some"
                },
                new SubCategory
                {
                    CategoryID =  categories.FirstOrDefault(c => c.CategoryName == "Electronics").CategoryID,
                    SubCategoryName = "Video Game Consoles && Accessories",
                    Description = "Some"
                },
            };
            _context.SubCategories.AddRange(subCategories);
            await _context.SaveChangesAsync();
        }

        private static async Task SeedProduct(ApplicationDbContext _context)
        {
            if (_context.Products.Any()) return;
            var subCategories = await _context.SubCategories.ToListAsync();
            var companies = await _context.Companies.ToListAsync();
            var products = new List<Product>
            {
                new Product
                {
                    ProductName = "iPhone 12 Pro Max",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Phones").SubCategoryID,
                    UnitPrice = 1695.66,
                    ImagePath = "iphone12.webp",
                    Description = "Some phone",
                    OnSale = true,
                    Star = 5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Apple").CompanyID,
                },
                new Product
                {
                    ProductName = "iPhone 11 Pro Max",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Phones").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "iphone11.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Apple").CompanyID,
                },
                new Product
                {
                    ProductName = "Xiaomi 9 Pro",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Phones").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "iphone11.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Xiaomi").CompanyID,
                },
                new Product
                {
                    ProductName = "Canon PowerShot SX540 Digital Camera",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Camera").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "canon_sx540.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Canon").CompanyID,
                },
                new Product
                {
                    ProductName = "Panasonic LUMIX FZ300",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Camera").SubCategoryID,
                    UnitPrice = 397,
                    ImagePath = "panasonic_fz300.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Panasonic").CompanyID,
                },
                new Product
                {
                    ProductName = "4K Digital Camera 48MP Camera",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Camera").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "4k_digitalcamera_48mp.jpg",
                    Description = "Some phone",
                    Star = 4.5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "CEDITA").CompanyID,
                },
                new Product
                {
                    ProductName = "TOZO T10 Bluetooth 5.0", 
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Headphones").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "tozo_t10.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 4.6,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "TOZO").CompanyID,
                },
                new Product
                {
                    ProductName = "TOZO T6 True Wireless",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Headphones").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "tozo_t6.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 4.5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "TOZO").CompanyID,
                },
                new Product
                {
                    ProductName = "Razer Kraken Tournament Edition",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Headphones").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "razer_kraken.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 4.5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Razer").CompanyID,
                },
                new Product
                {
                    ProductName = "Sony PlayStation 4 Pro (Red Dead Redemption 2 Bundle)",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Video Game Consoles && Accessories").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "playstation-4.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 4,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Sony").CompanyID,
                },
                new Product
                {
                    ProductName = "PlayStation 4 Pro 1TB Limited Edition",
                    SubCategoryID = subCategories.FirstOrDefault(s => s.SubCategoryName == "Video Game Consoles && Accessories").SubCategoryID,
                    UnitPrice = 1395.66,
                    ImagePath = "playstation-spider.jpg",
                    Description = "Some phone",
                    OnSale = false,
                    Star = 5,
                    Quantity = 10,
                    CompanyID = companies.FirstOrDefault(c => c.CompanyName == "Sony").CompanyID,
                },
            };

            _context.Products.AddRange(products);
            await _context.SaveChangesAsync();
        }

        private static async Task SeedCompany(ApplicationDbContext _context)
        {
            if (_context.Companies.Any()) return;
            var countries = await _context.Countries.ToListAsync();
            List<Company> companies = new List<Company>
            {
                new Company
                {
                    CompanyName = "Apple",
                    Year = 1976,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "USA").CountryID
                },
                new Company
                {
                    CompanyName = "Xiaomi",
                    Year = 2010,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "China").CountryID
                },
                new Company
                {
                    CompanyName = "Canon",
                    Year = 1987,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "China").CountryID
                },
                new Company
                {
                    CompanyName = "Panasonic",
                    Year = 1918,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "Japan").CountryID
                },
                new Company
                {
                    CompanyName = "CEDITA",
                    Year = 2005,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "United Kingdom").CountryID
                },
                new Company
                {
                    CompanyName = "TOZO",
                    Year = 2016,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "Spain").CountryID
                },
                new Company
                {
                    CompanyName = "Razer",
                    Year = 2010,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "USA").CountryID
                },
                new Company
                {
                    CompanyName = "Sony",
                    Year = 2000,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "Sony").CountryID
                },
            };
            _context.Companies.AddRange(companies);
            await _context.SaveChangesAsync();
        }

        private static async Task SeedCountry(ApplicationDbContext _context)
        {
            if (_context.Countries.Any()) return;

            var countries = new List<Country>
            {
                new Country
                {
                    CountryName = "Spain"
                },
                new Country
                {
                    CountryName = "United Kingdom"
                },
                new Country
                {
                    CountryName = "Japan"
                },
                new Country
                {
                    CountryName = "China"
                },
                new Country
                {
                    CountryName = "USA"
                },
            };
            _context.Countries.AddRange(countries);
            await _context.SaveChangesAsync();
        }

    }
}

Класс продукта:

using E_Store2021.ViewModels;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace E_Store2021.Models
{
    public class Product
    {
        public int ProductID { get; set; }

        [Required]
        [StringLength(100)] 
        [Display(Name = "Name")]
        public string ProductName { get; set; }

        public string Description { get; set; }

        public string ImagePath { get; set; }

        [Display(Name = "Price")]
        public double UnitPrice { get; set; }

        public bool OnSale { get; set; }

        public double Star { get; set; }

        public int Quantity { get; set; }

        public int? SubCategoryID { get; set; }

        public int? CompanyID { get; set; }

        public virtual Company Company { get; set; }

        public virtual SubCategory SubCategory { get; set; }
    }
}

Класс Компания:

using System.Collections.Generic;


namespace E_Store2021.Models
{
    public class Company
    {
        public int CompanyID { get; set; }

        public string CompanyName { get; set; }

        public int Year { get; set; }

        public int? CountryID { get; set; }

        public virtual Country Country { get; set; }

        public virtual ICollection<Product> Products { get; set; }
    }
}

Класс Страна:

using System.Collections.Generic;

namespace E_Store2021.Models
{
    public class Country
    {

        public int CountryID { get; set; }

        public string CountryName { get; set; }

        public virtual ICollection<Company> Companies { get; set; }

    }
}

Спасибо за любую помощь.

0
Evgeny20 24 Фев 2021 в 03:01

2 ответа

Лучший ответ

У вас ошибка:

new Company
                {
                    CompanyName = "Sony",
                    Year = 2000,
                    CountryID = countries.FirstOrDefault(c => c.CountryName == "Sony").CountryID
                },
1
Sergey 24 Фев 2021 в 00:30

Объявите свойства навигации по вашей коллекции следующим образом:

public virtual ICollection<Product> Products { get; } = new HashSet<Product>();

Таким образом, они начинаются пустыми, а не нулевыми.

2
David Browne - Microsoft 24 Фев 2021 в 00:33