我如何告诉 EF Core 关于同一类型的两个属性?

How do I tell EF Core about two properties of the same type?

我有一组代表法律案件的模型。用户可以对案例执行的操作之一是生成文档。此操作保存为 History 实体,关联的 HistoryFile 实体包含有关文件的数据。其他操作可能会产生一个 History 个实体,其中有零个或多个关联的 HistoryFile 个实体。

这两个 类 的简化版本看起来像这样...

  public class History {
    public int Id { get; set; }
    public ObservableCollection<HistoryFile> HistoryFiles { get; set; }
  }

  public class HistoryFile {
    public int Id { get; set; }
    public int HistoryId { get; set; }
    public History History { get; set; }
  }

下一个要求是用户可以选择之前生成的文档并继续处理它。我遇到困难的一点是 HistoryFile 实体需要引用回持有先前版本的 History 实体。这意味着我需要向 HistoryFile 实体添加两行代码...

  public class HistoryFile {
    public int Id { get; set; }
    public int HistoryId { get; set; }
    public History History { get; set; }
    public int? PreviousHistoryId { get; set; }
    public virtual History PreviousHistory { get; set; }
  }

这意味着从 HistoryFileHistory 有两个链接,其中一个是父 History 实体(通过 History 属性) 和一个可选的 PreviousHistory 属性.

我不知道如何为 EF Core 设置它。按照现在的代码,当我尝试添加迁移时,出现以下错误...

Cannot create a relationship between 'History.HistoryFiles' and 'HistoryFile.PreviousHistory' because a relationship already exists between 'History.HistoryFiles' and 'HistoryFile.History'. Navigation properties can only participate in a single relationship. If you want to override an existing relationship call 'Ignore' on the navigation 'HistoryFile.PreviousHistory' first in 'OnModelCreating'.

我尝试将以下内容添加到我的 DbContext...

builder.Entity<HistoryFile>(entity => {
  entity.HasOne(hf => hf.History)
    .WithMany(h => h.HistoryFiles)
    .HasForeignKey(hf => hf.HistoryId)
    .OnDelete(DeleteBehavior.Restrict);
  entity.HasOne(hf => hf.PreviousHistory)
    .WithMany(h => h.HistoryFiles)
    .HasForeignKey(hf => hf.PreviousHistoryId)
    .OnDelete(DeleteBehavior.Restrict);
});

...但没有任何区别。

谁能告诉我如何配置它以便 EF Core 知道两个实体之间有两个不同的链接?

我在 .NET5 项目中使用 EF Core 5.0.7,以防它产生影响。

谢谢

知道了。

我需要将以下两行添加到 History class...

public virtual ICollection<HistoryFile> HistoryFilesParentHistory { get; set; }
public virtual ICollection<HistoryFile> HistoryFilesPreviousHistory { get; set; }

...然后将我添加到 DbContext 的代码更改为如下所示...

builder.Entity<HistoryFile>(entity => {
  entity.HasOne(hf => hf.History)
    .WithMany(h => h.HistoryFilesParentHistory)
    .HasForeignKey(hf => hf.HistoryId)
    .OnDelete(DeleteBehavior.Restrict);
  entity.HasOne(hf => hf.PreviousHistory)
    .WithMany(h => h.HistoryFilesPreviousHistory)
    .HasForeignKey(hf => hf.PreviousHistoryId)
    .OnDelete(DeleteBehavior.Restrict);
});

这很好用。