Search code examples
c#.netentity-frameworkentity-framework-core

EF Core, Unidirectional many-to-many relationship


I have an entity setup like this:

public class Mission {
    public int Id { get; set; }
    ...
    public virtual ApplicationUser? Auditor { get; set; }
    public string? AuditorId
}

In this setup, each Mission can have 0 or 1 Auditor, and we don't care about going the other way (finding the missions associated with an auditor)

I wish to change it to this:

public class Mission {
    public int Id { get; set; }
    ...
    public ICollection<ApplicationUser> Auditor { get; set; }
}

So that each Mission instead has any number of Auditor, and again I don't care about going the other way.

But when I edit the Mission entity like this and generate a migration with EF Core, the migration contains this:

            migrationBuilder.AddColumn<int>(
                name: "mission_id",
                table: "AspNetUsers",
                type: "integer",
                nullable: true);

The migration is adding a Column "mission_id" in the AspNetUsers table, but that cannot be correct because each user is potentially linked to multiple missions, and anyway I don't care about this side of the relationship so I'd rather not have it.

The problem is that I don't know how to correct the migration or how to generate a correct one for my use case ... (because there's also the ModelSnapshot that I would need to change)

Edit

I found this section of documentation which seems like what I want: https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many#unidirectional-many-to-many

But it doesn't even compile ? this syntax public List<Tag> Tags { get; } = []; seems incorrect

Edit 2

Actually the syntax was correct (Rider linter wasn't), but the generated migration is still wrong !


Solution

  • I was missing the other part shown in the documentation:

    builder.Entity<Mission>().HasMany(m => m.Auditors).WithMany();
    

    adding this in OnModelCreating() and re-generating the migration worked !