Skip navigation has no foreign key defined

4.6k Views Asked by At

Context

I am following the examples of the new Many-to-Many relationship modelling in Entity Framework Core, referenced here:

https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key#many-to-many

and by the team building it here (expand the July 23 2020 post): https://github.com/dotnet/efcore/issues/19549

I have done this with a new .NET Web API project - the only change being that in my model I am using Staff and Team objects rather than the Post and Tag objects in the example.

My setup

  • macOS 10.15.7 (Catalina)
  • .NET Framework 5.0.101
  • EF version 5.0.1

The problem

When I run a migration, EF creates the lookup table in the generated SQL code as the documentation describes, even though there is no lookup object defined. This is great.

However, after I apply the SQL changes and run the app, when I access an API endpoint I get an error saying:

The skip navigation 'Staff.Teams' has no foreign key defined.

I am confused by this as the examples do not have foreign keys defined in their models.

I've done some looking around but haven't managed to find a similar issue.

Wondering if this could be an issue with .NET on macOS.

Thanks.

1

There are 1 best solutions below

0
On

It's better to share your model and configuration if exists. but at all, you can set many-to-many relation in ef 5 by convention (without configuration). you just need to set Collection in each entity and ef automatically create the third table for this relation.
because you got not defined foreign key, I guess you set configuration. I only can share the sample, I hope this helps you.

// MODEL
namespace EFConfiguration.Core.Domain.Relations
{
    public class Course
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Tag> Tags { get; set; }
    }

    public class Tag
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public List<Course> Courses { get; set; }
    }

    public class CourseTag
    {
        public int CourseId { get; set; }
        public int TagId { get; set; }
        public Course Courses { get; set; }
        public Tag Tag { get; set; }
    }
}

and configuration:

// CONFIG
public class CourseConfig : IEntityTypeConfiguration<Course>
{
    public void Configure(EntityTypeBuilder<Course> builder)
    {
        builder.HasMany(x => x.Tags).WithMany(x => x.Courses)
            .UsingEntity<CourseTag>(
            r => r.HasOne(x => x.Tag).WithMany().HasForeignKey(x => x.TagId),
            l => l.HasOne(x => x.Courses).WithMany().HasForeignKey(x => x.CourseId)); 
    }
}