简体   繁体   English

在 Entity Framework Core 中播种关系数据

[英]Seeding Relational Data in Entity Framework Core

I've found several SO posts on this but can't identify what I'm doing wrong here.我已经找到了几个关于此的 SO 帖子,但无法确定我在这里做错了什么。

I'm trying to seed two tables with an item each.我正在尝试为两张桌子播种,每张桌子都有一个项目。 The second item contains a lookup to the first.第二项包含对第一项的查找。 I can seed the parent with no issue, but cannot figure out the correct syntax to seed the child.我可以毫无问题地播种父母,但无法找出正确的语法来播种孩子。

Here is the code I use to seed the parent这是我用来播种父母的代码

   modelBuilder.Entity<Group>().HasData(new Group
        {
            Id = 1,
            Name = "Any",
            IsDeleted = false
        });

And here is the code to seed the child - this fails:这是播种孩子的代码 - 这失败了:

 modelBuilder.Entity<ShiftTypeDb>().HasData(new 
        {
            Id = 1,
            Name = "Any",
            GroupId = 1,

            IsDeleted = false
        });

Following the advice from the docs I've used an anonymous object instead of the class itself.根据 文档的建议,我使用了匿名 object 而不是 class 本身。 I've also tried using the navigation property and both the foreign key and the nav prop at the same time.我也尝试过同时使用导航属性以及外键和导航属性。 The Group with id=1 is definitely in the db already so it isn't a question of the parent item not existing. id=1 的组肯定已经在数据库中,所以这不是父项不存在的问题。

The error message I get is:我得到的错误信息是:

Insert or update on table "shifttypes" violates foreign key constraint "fk_shifttypes_groups_groupid"在表“shifttypes”上插入或更新违反了外键约束“fk_shifttypes_groups_groupid”

And the SQL generated for the seed is而为种子生成的 SQL 是

INSERT INTO shifttypes (id, groupid, isdeleted, name)
VALUES (1, 0, FALSE, 'Any');

It is clearly inserting a '0' as the GroupId, despite it being hardcoded as '1' in the seed;尽管它在种子中被硬编码为“1”,但它显然插入了一个“0”作为 GroupId; I cannot figure out why this is the case.我无法弄清楚为什么会这样。 Below is the code for the two entities that represent these two tables:下面是代表这两个表的两个实体的代码:

public class Group
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeleted { get; set; }
    public ICollection<ApplicationUser> Users { get; set; }

    public Group()
    {
    }

    public Group(string name)
    {
        Name = name;
    }
}

public class ShiftTypeDb
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeleted { get; set; }
    public int GroupId { get; set; }
    public Group Group { get; set; }

    public ShiftTypeDb()
    {
    }
}

This code was tested in Visual Studio and worked properly.此代码已在 Visual Studio 中测试并正常运行。 After fixing all bugs you have to delete existing db and migration and create the new one using Add-Migration InitialCreate option.修复所有错误后,您必须删除现有数据库和迁移并使用 Add-Migration InitialCreate 选项创建新的。

You have one-to-one relation instead of one-to-many.你有一对一的关系,而不是一对多。 To fix the bug add ShiftTypeDb collection to the Group class:要修复该错误,请将 ShiftTypeDb 集合添加到组 class:

    public class Group
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsDeleted { get; set; }
    public virtual ICollection<ApplicationUser> Users { get; set; }

    public virtual ICollection<ShiftTypeDb> ShifTypeDbs { get; set; }

   ...other properties
}

ans use ShiftTypeDb instead of anonymous type. ans 使用 ShiftTypeDb 而不是匿名类型。 Anonymous types are used only if your class have shadow properties.仅当您的 class 具有阴影属性时才使用匿名类型。 And be sure that group is ahead of TypeDB并确保该组领先于 TypeDB

modelBuilder.Entity<ShiftTypeDb>(
                entity =>
                {
                    entity.HasOne(d => d.Group)
                        .WithMany(p => p.ShiftTypeDbs)
                        .HasForeignKey("GroupId");
                });
 

modelBuilder.Entity<ShiftTypeDb>().HasData(new ShiftTypeDb 
        {
            Id = 1,
            Name = "Any",
            GroupId = 1,
            IsDeleted = false
        })

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

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