I've started to use .NET Core 2 and databases for the first time and looked at examples like: Getting Started with EF Core on .NET Core Console App with a New database. I've got a few models, like
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
But if I load an object, like Post post = context.Post.SingleOrDefault(s => s.PostId == id) then post.Blog is null. But if I before reading from the database, expand context.Blogs in the debugger, then post.Blog is a valid object after reading from the database with the above command.
So it feels like I need to read the blogs from the database to load those so the reference from Post will be correct. What is the correct way of doing this?
Second question: how to get the database context from anywhere? Should I have a default constructor with a connection string set in the constructor and create a new context all the time?