首页 > 解决方案 > 无法确定导航所代表的关系

问题描述

我有两个表 - 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。遵循命名约定通常就足够了。

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

我错过了什么?

标签: c#asp.net-coreef-core-5.0

解决方案


您需要在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- 此关系另一端的集合导航属性的名称。如果为 null 或未指定,则关系的另一端没有导航属性。

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); 

推荐阅读