c# - 通过 Fluent API 的 EF Core 外键

标签 c# entity-framework-core ef-core-2.0 ef-core-2.1

我有两门课:

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-onesingle navigation property的关系、主要实体 Item 和依赖实体 ItemStats,使用所谓的 shared primary key association ,其中从属实体 PK 也是主体实体的 FK。

用于一对一关系的 Fluent API 包括 HasOneWithOneHasForeignKeyHasPrincipalKey。请注意,这里 HasForeignKeyHasPrincipalKey 的通用类型参数(对于一对多关系通常被省略)很重要,因为它们标识哪个实体是主体,哪个实体是主体。 - 依赖。

话虽这么说,您的模型的流畅配置是:

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/

相关文章:

c# - 如何限制基于 WPF 的应用程序中的光标移动?

include - 无法调用Entity Framework 7中的include方法

entity-framework - 选择里面包含在 EF Core 中

c# - 如何使用内存数据库中的Entity Framework核心自动递增列?

C# 控制台应用 + 事件处理

c# - 为什么我不能在显式实现接口(interface)的类中调用方法?

c# - .NET 正则表达式中的 (?i) 是什么意思?

c# - 网络核心 : Find Primary Key of Entity Framework Core and Reflection

c# - 在 ActionFilter 中间件中使用 DbContext