简体   繁体   English

EF Core 种子数据库 OneToMany 与预定义列表的关系

[英]EF Core Seed Database OneToMany Relationship with predefined Lists

I am trying to seed a OneToMany Relationship in my Database with defined List<> and I get the following Error-Msg我正在尝试使用已定义的 List<> 在我的数据库中播种 OneToMany 关系,我收到以下错误消息

'The seed entity for entity type 'Country' cannot be added because it has the navigation 'WineRegions' set. '无法添加实体类型'Country'的种子实体,因为它设置了导航'WineRegions'。 To seed relationships you need to add the related entity seed to 'WineRegion' and specify the foreign key values {'CountryId'}.要为关系播种,您需要将相关实体种子添加到“WineRegion”并指定外键值 {'CountryId'}。 Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the involved property values.'考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看所涉及的属性值。

I used this page to create my classes: https://www.learnentityframeworkcore.com/relationships#one-to-many ... I can only guess that I somehow need to define the keys manually even though it should work automatically...我用这个页面来创建我的类: https://www.learnentityframeworkcore.com/relationships#one-to-many ...我只能猜测我需要手动定义键,即使它应该自动工作.. .

Here are my two classes.这是我的两节课。 WineRegions contains one Country and Country contains a collection of WineRegions: WineRegions 包含一个 Country 和 Country 包含 WineRegions 的集合:

public class WineRegion
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int WineRegionId { get; set; }

    public string WineRegionName { get; set; }   

    public int CountryId { get; set; }
    public Country Country { get; set; }
}

public class Country
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CountryId { get; set; }

    [Required]
    [MaxLength(255)]
    public string CountryName { get; set; }

    [Required]
    [MaxLength(2)]
    public string ISO3166Alpha2 { get; set; }

    public ICollection<WineRegion> WineRegions { get; set; }
}

During the Seeding I don't want to use hardcoded Objects like (btw this code works...):在播种期间,我不想使用硬编码的对象,例如(顺便说一句,此代码有效......):

        modelBuilder.Entity<Country>().HasData(
            new { Id = 1, Name = "France", ISO3166Alpha2 = "FR" }
            );

        modelBuilder.Entity<WineRegion>().HasData(
            new { Id = 1, Name = "Bordeaux", CountryId = 1 }
            );

As I mentioned before I want to use List which I generate during a JSON Parsing process.正如我之前提到的,我想使用在 JSON 解析过程中生成的列表。

So this is what I do:所以这就是我所做的:

        modelBuilder.Entity<Country>().HasData(listOfCountries);  // List<Country>
        modelBuilder.Entity<WineRegion>().HasData(listOfWineRegions); //List<WineRegion>

My JSON looks like this:我的 JSON 看起来像这样:

  "wineregions": [
    {
      "id": 1,
      "country": "France",
      "iso2": "FR",
      "region": [
        {
          "id": 1,
          "name": "Bordeaux"
        },
        {
          "id": 2,
          "name": "Burgundy"
        },
        {
          "id": 4,
          "name": "Burgundy"
        },
        {
          "id": 5,
          "name": "Beaujolais"
        },
        {
          "id": 6,
          "name": "Champagne"
        },
        {
          "id": 7,
          "name": "Loire"
        },
        {
          "id": 8,
          "name": "Alsace"
        },
        {
          "id": 9,
          "name": "Rhône"
        },
        {
          "id": 10,
          "name": "Provence"
        },
        {
          "id": 11,
          "name": "Languedoc-Roussillon"
        },
        {
          "id": 12,
          "name": "Jura"
        }
      ]
    },
    {
      "id": 2,
      "country": "Italy",
      "iso2": "IT",
      "region": [
        {
          "id": 1,
          "name": "Piedmont"
        },
        {
          "id": 2,
          "name": "Barolo"
        },
        {
          "id": 3,
          "name": "Barbaresco"
        },
        {
          "id": 4,
          "name": "Tuscany"
        },
        {
          "id": 5,
          "name": "Veneto"
        },
        {
          "id": 6,
          "name": "Friuli-Venezia"
        },
        {
          "id": 7,
          "name": "Giulia"
        },
        {
          "id": 8,
          "name": "Abruzzo"
        },
        {
          "id": 9,
          "name": "Sicily"
        },
        {
          "id": 10,
          "name": "Lambrusco"
        }
      ]
    }
  ]
} 


Thanks in advance

Your WineRegionId and ConutryId are Identity and it generated automatically by SQL.您的WineRegionIdConutryId是 Identity,它由 SQL 自动生成。

When your database keys are identity Id = 1 doesn't work.当您的数据库键是身份Id = 1不起作用

You Should remove identity from CountryId and WineRegionId .您应该从CountryIdWineRegionId中删除身份。

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CountryId { get; set; }
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int WineRegionId { get; set; }

Another way另一种方式

You can change your code to this.您可以将代码更改为此。

Country country = new Country { Name = "France", ISO3166Alpha2 = "FR" };
modelBuilder.Entity<Country>().HasData(country);

modelBuilder.Entity<WineRegion>().HasData(
            new { Name = "Bordeaux", Country = country }
            );

in this case ConutryId and WineRegionId generated automatically by SQL and relations between Conutry and WineRegion created by this line在这种情况下,由SQL自动生成的ConutryIdWineRegionId以及由该行创建的ConutryWineRegion之间的关系

new { Name = "Bordeaux", Country = country/*<--NOTE THIS*/ }

So i figured out how to fix it but I don't exactly understand why it has to be like this... A big "thank you" to Farhad Zamani!所以我想出了如何解决它,但我不完全理解为什么它必须是这样的......非常感谢 Farhad Zamani!

  1. I changed the identity attribute to: [DatabaseGenerated(DatabaseGeneratedOption.None)] -我将身份属性更改为: [DatabaseGenerated(DatabaseGeneratedOption.None)] -
  2. I needed to remove the [Key] Attributes from both classes我需要从两个类中删除 [Key] 属性
  3. I needed to apply the [NotMapped] attribute to the nested class Country within the WineRegion class我需要将 [NotMapped] 属性应用于 WineRegion class 内的嵌套 class 国家/地区
  4. I needed to apply the ForeignKey Attribute to CountryId property.我需要将 ForeignKey 属性应用于 CountryId 属性。

     public class WineRegion { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int WineRegionId { get; set; } public string WineRegionName { get; set; } [NotMapped] public Country Country { get; set; } [ForeignKey("CountryId")] public int CountryId { get; set; } } public class Country { [DatabaseGenerated(DatabaseGeneratedOption.None)] public int CountryId { get; set; } [Required] [MaxLength(255)] public string CountryName { get; set; } [Required] [MaxLength(2)] public string ISO3166Alpha2 { get; set; } public List<WineRegion> WineRegions { get; set; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM