Search code examples
c#.net-coreentity-framework-coreef-code-firstentity-framework-migrations

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


I started using EF Core with the database-first approach, I had two tables CalendarDates and Deals. A deal has multiple date-related properties for which separate foreign key relationships have been been set-up. In the below example StartDate and EndDate.

The scaffolded DbContext showed the class definitions as such:

    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!;
    }

I now want to make the move to code-first. But when I add the migration the following error is thrown:

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'.

If I comment-out the fields belonging to EndDate in both classes, it works just fine. So it seems that I cannot use more than one MANY:ONE relationship (many=Deals,one=CalendarDates) here. Althoug it worked just fine when scaffolded from an existing database with existing FK constraints.

What am I missing here?

Cheers


Solution

  • Please try configuring relationships in the OnModelCreating like this

    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);
    

    Edit : checked&fixed