Связь многие ко многим Code First

Имеется две модели данных, между ними пытаюсь реализовать связь многие ко многим

 public class Post
    {
        [Key]
        public int Id { get; set; }
        public byte[] Photo { get; set; }
        [Column(TypeName = ("integer"))]
        public int UserId { get; set; }
        [Column(TypeName = ("varchar(250)"))]
        public string Description { get; set; }
        public virtual ICollection<User> Users { get; set; }
        public Post()
        {
            Users = new List<User>();
        }
    }


    public class User
    {
        [Key]
        public int Id { get; set; }
        [Column(TypeName = ("varchar(250)"))]
        public string Login { get; set; }
        [Column(TypeName = ("varchar(250)"))]
        public string Password { get; set; }
        [Column(TypeName = ("varchar(250)"))]
        public virtual ICollection<Post> Posts { get; set; }
        public User()
        {
            Posts = new List<Post>();
        }
    }

При миграции в БД(Postgresql) выскакивает следующая ошибка:

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

Ответы (1 шт):

Автор решения: funforlifefix

Вам необходимо добавить ещё одну сущность которая будет связывать 2 других. Пример:

public class Person
{
   [Key]
   public int ID { get; set; }
   public ICollection<UserPost> UserPosts { get; set; }
}

public class User
{
   [Key]
   public int ID { get; key; }
   public ICollection<UserPost> UserPosts { get; set; }
}

public class UserPost
{
   public int UserID { get; set; }
   public virtual User User { get; set; }
   public int PostID { get; set }
   public virtual Post Post { get; set; }
}

Затем в классе вашего DbContext в методе onModelCreating указать связь:

protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserPost>()
            .HasKey(x => new { x.UserID, x.PostID });

        modelBuilder.Entity<UserPost>()
            .HasOne(x => x.User)
            .WithMany(x => x.UserPosts)
            .HasForeignKey(x => x.UserID);

        modelBuilder.Entity<UserPost>()
            .HasOne(x => x.Post)
            .WithMany(x => x.UserPosts)
            .HasForeignKey(x => x.PostID);
    }
→ Ссылка