0

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

 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'.
3
  • Вы не указали, по какому ключу вы делаете связь. Поэтому EF ругается и предлагает пометить коллекцию как NotMapped 20 мая 2020 в 16:04
  • @funforlifefix Я так понимаю, нужно присвоить ForeignKey обоим Id, с ссылкой на модели друг друга, но лучше подскажите как это сделать) 20 мая 2020 в 16:19
  • @funforlifefix Сделал как сказал выше, вышла таже ошибка 20 мая 2020 в 16:29

1 ответ 1

0

Вам необходимо добавить ещё одну сущность которая будет связывать 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);
    }
4
  • P.S. Настройка связей в данном методе производится через Fluent API. Здесь же можно настроить ключи сущностей User и Post вместо указания атрибутов [Key] 20 мая 2020 в 16:42
  • Я понял, а как теперь при обращении к одной таблице получать сразу данные из второй? Я руководствовался этой статьёй, но у меня так не выходит metanit.com/sharp/entityframework/3.8.php 20 мая 2020 в 16:53
  • User user = dbContext.User.Where(x => x.iD == userId).FirstOrDefault(); Post = user?.UserPosts?.FirstOrDefault()?.Post; Добавьте ещё нужные условия поиска и проверки на null 20 мая 2020 в 16:55
  • Если не настроены EF proxy добавляйте Include . dbContext.User.Include(x => x.UserPosts).Where(...) 20 мая 2020 в 16:59

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.