entity-framework - 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
}
解决方案
如何使用 Fluent API 替换
[ForeignKey("aServiceRun")]
注解?
您正在寻找HasForeignKey fluent API。但是为了访问它(以及其他关系配置 API),您需要使用Has{One|Many}
后跟定义关系With{One|Many}
。对于一对一的关系,您还需要提供泛型类型参数HasForeignKey
:
使用 Fluent API 配置关系时,使用
HasOne
和WithOne
方法。配置外键时,您需要指定依赖实体类型 - 请注意
HasForeignKey
下面列表中提供的通用参数。在一对多关系中,很明显具有引用导航的实体是依赖实体,而具有集合的实体是主体。但这不是一对一的关系——因此需要明确定义它。
请注意,包含 FK 的实体始终是从属的,因此对于您的模型,ServiceRun
它是主体,Service
是从属,流畅的配置如下:
modelBuilder.Entity<Service>()
.HasOne(s => s.aServiceRun) // navigation property
.WithOne() // no navigation property
.HasForeignKey<Service>(s => s.RunId); // foreign key
推荐阅读
- javascript - 删除记录而不刷新 PHP/Javascript
- android - 如何按组(文件夹)组织已安装的 Android 应用程序?
- bash - Cpu 使用简单 bash “整数预期错误”
- database - 有没有办法将 RingCentral 数据与承诺数据库集成?
- android - Jetpack Compose 中的未绑定波纹/指示(相当于 selectableBackgroundBorderless)
- json - AEM JCR - 以 JSON 格式获取响应
- r - 如何在y轴上将小数更改为数字
- sql - 跟踪属性变化
- sql - 无论原始列名如何,SQL 都将所有列转置为行
- javascript - 使用带有 [] 和不使用 useState 以及使用 {} 的区别