首页 > 解决方案 > EF Core 3.0 1:0 与fluent的关系

问题描述

EF Core 3.0...我找不到这个完全法线映射的准确答案。
Principal to Dependent,没有指向 Principal 的反向指针,1:0 关系,一个类型对象/查找表设置。问题是对象键名“RunId”与 EFCore 生成的键名“ServiceRunId”不同

如何使用 Fluent API 替换 [ForeignKey("aServiceRun")] 注释?

这是我当前的 Fluent 设置,但我不知道在哪里放置 ForeignKey 映射。

aBuilder.Entity<ServiceRun>().HasKey(new string[] { "RunId "});

aBuilder.Entity<Service>().HasOne(s => s.aServiceRun);


Class Service {        
  public int ServiceId {get; set;}

  [ForeignKey("aServiceRun")]
  public int RunId { get; set; }

  public virtual ServiceRun aServiceRun { get; set; }
}

Class ServiceRun {
  public int RunId { get; set; }

  public string description {get ;set; }
}

表:

Service {
  ServiceId int

  RunId int
}

SerivceRun {
  RunId int

  Description string
}

标签: entity-frameworkmappingfluentef-core-3.1

解决方案


如何使用 Fluent API 替换[ForeignKey("aServiceRun")]注解?

您正在寻找HasForeignKey fluent API。但是为了访问它(以及其他关系配置 API),您需要使用Has{One|Many}后跟定义关系With{One|Many}。对于一对一的关系,您还需要提供泛型类型参数HasForeignKey

使用 Fluent API 配置关系时,使用HasOneWithOne方法。

配置外键时,您需要指定依赖实体类型 - 请注意HasForeignKey下面列表中提供的通用参数。在一对多关系中,很明显具有引用导航的实体是依赖实体,而具有集合的实体是主体。但这不是一对一的关系——因此需要明确定义它。

请注意,包含 FK 的实体始终是从属的,因此对于您的模型,ServiceRun它是主体,Service是从属,流畅的配置如下:

modelBuilder.Entity<Service>()
    .HasOne(s => s.aServiceRun) // navigation property
    .WithOne() // no navigation property
    .HasForeignKey<Service>(s => s.RunId); // foreign key

推荐阅读