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

Visual studio 2017 当依赖实体对父实体有多个引用时,EF Core错误更新数据库,visual-studio-2017,entity-framework-core,asp.net-core-2.0,Visual Studio 2017,Entity Framework Core,Asp.net Core 2.0,我是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; }

我是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; }
}
谁能帮我一下我做错了什么,以及如何以最好的方式解决这个问题


感谢

Entity Framework足够智能,能够根据您的模型生成相应的表和表之间的关系时,解决可能出现的问题

然而,这不是一个错误,这更像是一个警告,作为开发人员,您必须进行一些额外的配置,以生成正确的关系。这是由于这一部分:

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

public int ContributorId { get; set; }
public User Contributor { get; set; }
因为您使用的是相同的类型,
User
EF必须得到指示,当其中一个属性发生更改(创建、删除、更新)时,如何操作。这也是因为您可以为作者和贡献者使用相同的
键,在这种情况下,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);
}

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

如您所见,错误是关于
WorkflowRules
表,Post和User表不涉及。我只是以这些表为例。无论如何,我已经更新了错误。
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);
}