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?
Take a look here for detailed explanation: https://learn.microsoft.com/en-us/ef/core/querying/related-data
A few examples from the link above:
Eager loading
using (var context = new BloggingContext())
{
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ToList();
}
Explicit loading
using (var context = new BloggingContext())
{
var blog = context.Blogs
.Single(b => b.BlogId == 1);
context.Entry(blog)
.Collection(b => b.Posts)
.Load();
}
Lazy loading is not yet supported. It should be coming in v2.1.
Just to keep this updated for future reference, EF Core now supports lazy loading.
https://learn.microsoft.com/en-us/ef/core/querying/related-data
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLazyLoadingProxies()
.UseSqlServer(myConnectionString);
This should solve the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With