我有两门课:
public class Item
{
public int Id { get; set; }
public string ItemName { get; set; }
}
public class ItemStats //inhenrit from Item
{
public int Id { get; set; }
public int MaxEnhanceLevel { get; set; }
public Item Item { get; set; }
}
这是一个 TPT,但由于不支持开箱即用,所以我无法使用继承。我知道如何使用数据注释来实现这一点
[ForeignKey(nameof(Item))]
public int Id { get; set; }
但是我如何通过 FluentAPI 做到这一点?我不想在我的实体类中添加数据注释。
最佳答案
你拥有的是 One-to-one与single navigation property的关系、主要实体 Item
和依赖实体 ItemStats
,使用所谓的 shared primary key association ,其中从属实体 PK 也是主体实体的 FK。
用于一对一关系的 Fluent API 包括 HasOne
、WithOne
、HasForeignKey
和 HasPrincipalKey
。请注意,这里 HasForeignKey
和 HasPrincipalKey
的通用类型参数(对于一对多关系通常被省略)很重要,因为它们标识哪个实体是主体,哪个实体是主体。 - 依赖。
话虽这么说,您的模型的流畅配置是:
modelBuilder.Entity<ItemStats>()
.HasOne(e => e.Item)
.WithOne()
.HasForeignKey<ItemStats>(e => e.Id);
关于c# - 通过 Fluent API 的 EF Core 外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53231859/