无法确定导航所代表的关系

Unable to determine the relationship represented by navigation

我有两个表 - Products 和 ProductRelations。他们是这样的:

public class Product
{
    public int Id { get; set; }
    public string SKU { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }

    public IList<ProductRelation> ProductRelations { get; set; }
}

public class ProductRelation
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public int ProductId { get; set; }
    public int RelatedProductId { get; set; }

    //[ForeignKey("ProductId")]
    public Product Product { get; set; }
    //[ForeignKey("RelatedProductId")]
    public Product RelatedProduct { get; set; }
}

我收到错误 InvalidOperationException: Unable to determine the relationship represented by navigation 'Product.ProductRelations' of type 'IList<ProductRelation>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

我从未使用过 OnModelCreating。遵循命名约定通常就足够了。

如果我从 ProductRelation class 中删除 public Product RelatedProduct { get; set; },错误就会消失。

我错过了什么?

您需要 Product 中的多个集合。尝试这样的事情:

public class Product
{
    public int Id { get; set; }
    public string SKU { get; set; }
    public string Name { get; set; }

    [InverseProperty(nameof(ProductRelation.Product)]
    public IList<ProductRelation> ProductRelationsLeft { get; set; }
    [InverseProperty(nameof(ProductRelation.RelatedProduct)]
    public IList<ProductRelation> ProductRelationsRight { get; set; }
}

您也可以通过 fluent api 尝试下一个设置,提供默认关系集合参数 (collection):

collection - The name of the collection navigation property on the other end of this relationship. If null or not specified, there is no navigation property on the other end of the relationship.

modelBuilder.Entity<ProductRelation>()
     .HasOne(pt => pt.Product)
     .WithMany() // leave empty
     .HasForeignKey(pt => pt.ProductId)
     .OnDelete(DeleteBehavior.Restrict); 

modelBuilder.Entity<ProductRelation>()
    .HasOne(pt => pt.RelatedProduct)
    .WithMany(t => t.ProductRelations)
    .HasForeignKey(pt => pt.RelatedProductId);