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

EF Core 3.0 1:0 relationship with fluent

EF Core 3.0...我找不到这个完全正常映射的精确答案。
Principal 到 Dependent,没有指向 Principal 的后向指针,1:0 关系,类型对象/查找 table 设置。问题是对象键名 "RunId" 不同于 EFCore 生成的键名 "ServiceRunId"

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

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

aBuilder.Entity().HasKey(新字符串[] { "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
}

How can I use Fluent API to replace the [ForeignKey("aServiceRun")] annotation?

您正在寻找 HasForeignKey fluent API. But in order to get access to it (and other relationship configuration APIs), you need to define the relationship by using Has{One|Many} followed by With{One|Many}. For one-to-one 关系,您还需要向 HasForeignKey 提供通用类型参数:

When configuring the relationship with the Fluent API, you use the HasOne and WithOne methods.

When configuring the foreign key you need to specify the dependent entity type - notice the generic parameter provided to HasForeignKey in the listing below. In a one-to-many relationship it is clear that the entity with the reference navigation is the dependent and the one with the collection is the principal. But this is not so in a one-to-one relationship - hence the need to explicitly define it.

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

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

我找到了上述问题的答案 - 我的 ServiceRun 对象上有一个未配置或被忽略的反向列表。我决定把它留在这里作为另一个例子。也许它会为某人提供一些价值。

这是从服务到 ServiceRunType 的 1:0,其中 table 名称和 property/field 名称不完全匹配。

表格

ServiceRun { //Does not match object name
int Id, 
string Desc
}
Service {
int Id, 
int RunId //Does not match object
}

对象

Class ServiceRunType{  //Does not match table name
public int Id {get; set;} 
public String Desc {get; set;}
}
Class Service{
public int Id {get; set;} 
public int RunTypeId {get; set;} //Does not match table
public virtual ServiceRunType aServiceRunType { get; set; }
}

流畅代码

modelBuilder.Entity<ServiceRunType>()
.ToTable("ServiceRun", schema: "load")
.HasKey(new string[] { "Id" });
modelBuilder.Entity<Service>()
.ToTable("Service", schema: "load") //Had to specify schema
.HasKey(new string[] { "Id" });
modelBuilder.Entity<Service>()
.Property("RunTypeId")
.HasColumnName("RunId");
modelBuilder.Entity<Service>()
.HasOne(s => s.aServiceRunType)
.WithOne()
.HasForeignKey<Service>(s => s.RunTypeId);