ASP.NET Core SQL Server 连接 - 迁移

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

当我使用 2 个不同的外键时遇到此错误。

在表“Comments”上引入 FOREIGN KEY 约束“FK_Comments_Posts_Id”可能会导致循环或多级联路径。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 约束。
无法创建约束或索引。查看之前的错误。

public class Comment
{
    public int Id { get; set; }
    public int PostId{ get; set; }
    public Post Post { get; set; } = null!;
    public int UserId { get; set; }
    public AppUser User { get; set; } = null!;
}

public class AppDbContext : IdentityDbContext<AppUser,UserRole,int>
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    public DbSet<Comment> Comments { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}`345`
asp.net-core entity-framework-core migration database-migration
1个回答
0
投票

您应该提供您引用的其余课程。 另外,在错误消息的末尾有查看以前错误的信息,它们还可以包含一些信息。

您在

AppUser
Post
中还有其他外键吗?
您是否定义了一些外键约束或级联行为?

我猜在这两个类中你也有主键 ID,所以你可以像这样简化

Comment
类:

public class Comment {
    public int Id { get; set; }
    [ForeignKey("PostId")]
    public Post Post { get; set; } = null!;
    [ForeignKey("UserId")]
    public AppUser User { get; set; } = null!;
}
© www.soinside.com 2019 - 2024. All rights reserved.