EF Core,单向多对多关系

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

我有一个像这样的实体设置:

public class Mission {
    public int Id { get; set; }
    ...
    public virtual ApplicationUser? Auditor { get; set; }
    public string? AuditorId
}

在此设置中,每个任务可以有 0 或 1 个审核员,我们不关心采取其他方式(查找与审核员关联的任务)

我想改成这样:

public class Mission {
    public int Id { get; set; }
    ...
    public ICollection<ApplicationUser> Auditor { get; set; }
}

这样每个任务都有任意数量的审计员,而且我也不关心走另一条路。

但是当我像这样编辑 Mission 实体并使用 EF Core 生成迁移时,迁移包含以下内容:

            migrationBuilder.AddColumn<int>(
                name: "mission_id",
                table: "AspNetUsers",
                type: "integer",
                nullable: true);

迁移正在 AspNetUsers 表中添加一列“mission_id”,但这不可能是正确的,因为每个用户都可能链接到多个任务,而且无论如何我不关心关系的这一面,所以我宁愿不这样做它。

问题是我不知道如何纠正迁移或如何为我的用例生成正确的迁移......(因为还有我需要更改的 ModelSnapshot)

编辑

我发现这部分文档似乎是我想要的:https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many#unidirection-many-to-many

但它甚至无法编译?这个语法

public List<Tag> Tags { get; } = [];
似乎不正确

编辑2

实际上语法是正确的(Rider linter 不是),但生成的迁移仍然是错误的!

c# .net entity-framework entity-framework-core
1个回答
0
投票

我缺少文档中显示的其他部分:

builder.Entity<Mission>().HasMany(m => m.Auditors).WithMany();

将其添加到 OnModelCreating() 中并重新生成迁移工作!

© www.soinside.com 2019 - 2024. All rights reserved.