EF Core code-first 与同一主体实体的多个外键关系

EF Core code-first multiple foreign key relationships to same principal entity

我开始使用 EF Core 和数据库优先方法,我有两个表 CalendarDatesDeals。交易具有多个与日期相关的属性,已为其设置单独的外键关系。在下面的示例中 StartDateEndDate.

scaffolded DbContext 显示了 class 定义:

    public class CalendarDate
    {
        public CalendarDate()
        {
            DealsStartedOnThatDate = new HashSet<Deal>();
            DealsEndedOnThatDate = new HashSet<Deal>();
        }

        [Key]
        public string Id { get; set; } = string.Empty;
        public DateTimeOffset Date { get; set; }
        public int Year { get; set; }

        public virtual ICollection<Deal> DealsStartedOnThatDate { get; set; }
        public virtual ICollection<Deal> DealsEndedOnThatDate { get; set; }
    }

    public class Deal
    {        
        [Key]
        public string Id { get; set; } = string.Empty;
        public string Name { get; set; } = string.Empty;

        public string StartDateId { get; set; } = string.Empty;
        public virtual CalendarDate StartDate { get; set; } = null!;

        public string EndDateId { get; set; } = string.Empty;
        public virtual CalendarDate EndDate { get; set; } = null!;
    }

我现在想转向代码优先。但是当我添加迁移时,会抛出以下错误:

Unable to determine the relationship represented by navigation property 'CalendarDate.DealsStartedOnThatDate' of type 'ICollection<Deal>'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

如果我在两个 classes 中注释掉属于 EndDate 的字段,它就可以正常工作。所以看来我不能在这里使用多个 MANY:ONE 关系 (many=Deals,one=CalendarDates)。尽管从具有现有 FK 约束的现有数据库构建脚手架时它工作得很好。

我在这里错过了什么?

干杯

请尝试在 OnModelCreating 中像这样配置关系

modelBuilder.Entity<Deal>().HasOne(cd => cd.StartDate)
            .WithMany(c => c.DealsStartedOnThatDate).HasForeignKey(d => d.StartDateId);

modelBuilder.Entity<Deal>().HasOne(cd => cd.EndDate)
           .WithMany(c => c.DealsEndedOnThatDate).HasForeignKey(d => d.EndDateId);

编辑:检查并修复