[英]Configure an EF Core one-to-one relationship with multiple columns (one with a constant value)
假设我有一个存储表/类和一个文件夹表/类。 一个存储总是有一个根文件夹(它在创建存储时创建,并且在存储被删除之前一直存在),并且一个文件夹可以有零个或多个子文件夹。
存储 class:
[Table("Storage")]
public class Storage
{
public int Id { get; set; }
public string Name { get; set; }
public Folder RootFolder { get; set; }
}
文件夹 class:
[Table("Folder")]
public class Folder
{
public int Id { get; set; }
public int StorageId { get; set; }
public string Name { get; set; }
public int? ParentFolderId { get; set; }
public virtual Collection<Folder> Children { get; set; }
}
存储表:
+----+-----------+
| Id | Name |
+----+-----------+
| 1 | Storage 1 |
| 2 | Storage 2 |
+----+-----------+
文件夹表:
+----+-----------+------+----------------+
| Id | StorageId | Name | ParentFolderId |
+----+-----------+------+----------------+
| 1 | 1 | | null |
| 2 | 1 | foo | 1 |
| 3 | 1 | bar | 1 |
| 4 | 1 | baz | 2 |
| 5 | 2 | | null |
+----+-----------+------+----------------+
如您所见,要获取存储的根文件夹,您需要使用Storage.Id = Folder.StorageId and ParentFolderId is null
。 使用 EF Core,如何在OnModelCreating
方法中配置这样的关系?
以下显然不起作用,因为ParentFolderId is null
不包含在关系定义中:
modelBuilder.Entity<Storage>(entity =>
{
entity.HasOne(d => d.RootFolder)
.WithOne()
.HasForeignKey<Storage>(d => d.StorageId);
});
我们在这里采用大约 2 个外键 (FK) 关系
Storage
和Folder
之间Folder
自引用关系因此,在定义关系时,您需要定义 2 个外键关系,使得StorageId column (FK of Storage table in Folder) is not nullable
,而ParentFolderId ( Self reference FK) is nullable
。
查找根文件夹更多的是查询逻辑,而不是 FK 定义。 因此,在查询时,添加一个附加条件,如.Where(s => s.ParentFolderId == null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.