A
A
artshelom2020-07-07 18:44:50
PostgreSQL
artshelom, 2020-07-07 18:44:50

How to make a connection between objects?

I'm trying to make One to many, But for some reason, if I don't recreate the db, then the connection doesn't work. What could be the problem. DB: postgress DB:

public MySqlContext(DbContextOptions options) : base(options)
    {
        // Database.EnsureDeleted(); // Это пересоздает таблицу, Если отключено. То не работает
        Database.EnsureCreated();
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Comment>()
            .HasOne<Article>(sc => sc.Article)
            .WithMany(s => s.Comments)
            .HasForeignKey(sc => sc.ArticleId);

        modelBuilder.Entity<Article>()
            .HasMany<Comment>(a => a.Comments)
            .WithOne(a => a.Article)
            .HasForeignKey(a => a.ArticleId);

        base.OnModelCreating(modelBuilder);
    }


If the database is recreated, then Comments returns a list, and if not, it returns null.

How to make it work?

It is necessary to link 2 tables so that when an Article is received, a list of comments is immediately loaded

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gotoxy, 2020-07-16
@artshelom

Database.EnsureCreated() does not recreate, but checks if the database exists and, if not, creates a new one, otherwise nothing happens.
In order for comments to be loaded along with articles, you must specify this explicitly:

var articles = context.Articles.Include(a => a.Comments).ToList();

https://docs.microsoft.com/en-us/ef/core/querying/...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question