EF Core 错误更新数据库,当依赖实体具有对父实体的多个引用时



我是EF Core的新手。我有两个表,几乎类似于以下两个表,如下所示:

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int AuthorId { get; set; }
    public User Author { get; set; }
    public int ContributorId { get; set; }
    public User Contributor { get; set; }
}
public class User
{
    public string Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [InverseProperty("Author")]
    public List<Post> AuthoredPosts { get; set; }
    [InverseProperty("Contributor")]
    public List<Post> ContributedToPosts { get; set; }
}

当我运行更新数据库命令时,我收到以下错误

Introducing FOREIGN KEY constraint 'FK_Post_User_AuthorId' on table 'Post' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

任何人都可以帮助我做错了什么以及如何以最佳方式解决这个问题?

谢谢

实体框架足够聪明,可以找出在生成表时可能会出现的问题以及它们之间的关系。

但是,这不是错误,这更像是一个警告,作为开发人员,您必须在其中进行一些其他配置才能生成正确的关系。这是由于这部分:

public int AuthorId { get; set; }
public User Author { get; set; }
public int ContributorId { get; set; }
public User Contributor { get; set; }

由于您使用的是相同类型,因此必须指示 EF User在更改(创建、删除、更新)其中一个属性时如何操作。发生这种情况也是因为作者和参与者可以使用相同的Key,在这种情况下,EF 必须知道如何处理它。

解决方案非常简单,添加一些额外的配置:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    // Relationships
    entity.HasOne(p => p.Author)
        .WithMany(p => p.AuthoredPosts)
        .HasForeignKey(p => p.AuthorId)
        .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Cascade);
    entity.HasOne(p => p.Contributor)
        .WithMany(p => p.ContributedToPosts)
        .HasForeignKey(p => p.ContributorId)
        .OnDelete(Microsoft.EntityFrameworkCore.Metadata.DeleteBehavior.Cascade);
}

您还可以指定更新发生时发生的情况。

最新更新