c# - 无法确定导航所代表的关系
问题描述
我有两个表 - 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
班级中删除,错误就会消失。
我错过了什么?
解决方案
您需要在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);
推荐阅读
- python - ValueError:输入形状的预期轴 -1 的值为 51948,但接收到的输入形状为(无,52)
- tensorflow - AutoKeras:TypeError:“NoneType”和“int”的实例之间不支持“<”
- gtkmm - 如何计算存储在 Gtk::Grid 中的小部件?
- pnpm - 有没有办法在 PNPM 中将特定包裹排除在吊装之外?
- android - 如何在我的应用程序上显示来自 Firebase 存储的图像?
- java - 连接到 KNX IP 路由器的异常 - 参数无效
- html - Bootstrap 导航栏崩溃无法正常工作 || 导航栏折叠不显示点击链接
- nestjs - typeorm 在自定义记录器中保存调用超过 1000 次
- c# - 转换 JSON 格式 - C# 中的动态类
- arrays - Julia 代码优化:是时候使用 SIMD 了吗?