Answer the question
In order to leave comments, you need to log in
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);
}
Answer the question
In order to leave comments, you need to log in
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();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question