Entity Framework создает новую запись для каждого внешнего ключа в другой таблице во время заполнения - PullRequest
0 голосов
/ 29 мая 2019

Я пытаюсь заполнить базу данных, используя EF.

У меня есть таблица товаров (телефоны) и таблица Category, которая различает товары разных типов.

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public DateTimeOffset? CreationDate { get; set; }
    public DateTimeOffset? UpdateDate { get; set; }

    public virtual List<IProduct> Products{ get; set; }

    public Category()
    {
        this.CreationDate = DateTimeOffset.UtcNow;
    }

}

public interface IProduct
{
    int ProductId { get; set; }
    string Brand { get; set; }
    string Model { get; set; }

    decimal? Price { get; set; }
    string Image { get; set; }

    int CategoryId { get; set; }
    Category Category { get; set; }
}

public class Phone: IProduct
{
    public int ProductId { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public string network_technology { get; set; }
    public string bands_2G { get;set; }
    public string bands_3G{ get; set; }
    public string bands_4G { get; set; }
    public string network_speed { get; set; }
    public string GPRS { get; set; }
    public string EDGE { get; set; }
    public string announced { get; set; }
    public string status { get; set; }
    public string dimentions { get; set; }
    public float? weight_g { get; set; }
    public float? weight_oz { get; set; }
    public string SIM { get; set; }
    public string display_type { get; set; }
    public string display_resolution { get; set; }
    public string display_size { get; set; }
    public string OS { get; set; }
    public string CPU { get; set; }
    public string Chipset { get; set; }
    public string GPU { get; set; }
    public string memory_card { get; set; }
    public string internal_memory { get; set; }
    public string RAM { get; set; }
    public string primary_camera { get; set; }
    public string secondary_camera { get; set; }
    public string loud_speaker { get; set; }
    public string audio_jack { get; set; }
    public string WLAN { get; set; }
    public string bluetooth { get; set; }
    public string GPS { get; set; }
    public string NFC { get; set; }
    public string radio { get; set; }
    public string USB { get; set; }
    public string sensors { get; set; }
    public string battery { get; set; }
    public string colors { get; set; }
    public decimal? Price { get; set; }
    public string Image { get; set; }
}

Я не знаю, что я делаю неправильно, но после обновления базы данных с консоли nuget для каждого затравленного продукта (телефона) создается новая запись категории . Это как раз то, что я хочу. Я хочу, чтобы на всех телефонах была одна categoryId, относящаяся к категории Phones. Кто-нибудь знает, что не так?

Category Table

Phones Table

Конфигурации типов объектов (свободный API):

public class CategoryConfiguration : EntityTypeConfiguration<Category>
{
    public CategoryConfiguration()
    {
        ToTable("Categories");
        HasKey(m => m.CategoryId);
    }
}

public class PhoneConfiguration : EntityTypeConfiguration<Phone>
{
    public PhoneConfiguration()
    {
        ToTable("Phones");
        HasKey(m => m.ProductId);
    }
}

Метод семян:

protected override void Seed(BestPhone.Data.BestPhoneDbContext context)
{
       context.Categories.AddOrUpdate(new Category(){Name = "Phones", CategoryId = 1});
       ...
       //getting records from a csv file and holding them in an array.
       var records = csvReader.GetRecords<Phone>().ToArray();

       foreach (var record in records)
       {
           record.CategoryId = 1;
       }

       context.Phones.AddRange(records);
       context.SaveChanges();
   }
}

1 Ответ

0 голосов
/ 29 мая 2019

Попробуйте добавить следующий метод в ваш CategoryConfiguration класс:

    public void Configure(EntityTypeBuilder<Category> builder)
    {
        builder
            .HasMany(s => s.Products)
            .WithOne(t => t.Category)
            .HasForeignKey(t => t.CategoryId);
    }

Я не уверен, но, похоже, система не учитывает ваш внешний ключ во время заполнения.

...