EF Core 3.0 1:0与流利的关系

问题描述 投票:1回答:1

EF Core 3.0 ...对于这种完全正常的映射,我找不到精确的答案。主体到从属,没有反向指向主体的指针,关系为1:0,设置了类型对象/查找表。问题是对象键名“ RunId”与EFCore生成的键名“ ServiceRunId”不同]

我如何使用Fluent API替换[ForeignKey(“ aServiceRun”)]批注?

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

aBuilder.Entity ()。HasKey(new string [] {“ RunId”});

aBuilder.Entity ()。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-framework mapping fluent ef-core-3.1
1个回答
0
投票
如何使用Fluent API替换[ForeignKey("aServiceRun")]注释?
您正在寻找HasForeignKey流利的API。但是,为了访问它(和其他关系配置API),您需要使用Has{One|Many}With{One|Many}来定义关系。对于one-to-one关系,还需要向HasForeignKey提供通用类型参数:

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

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

请注意,包含FK的实体始终是

dependent,因此对于您的模型,ServiceRun是主体,Service是从属,并且流畅的配置如下:

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

© www.soinside.com 2019 - 2024. All rights reserved.