简体   繁体   中英

.NET Core 2 EF, object references are null

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://docs.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://docs.microsoft.com/en-us/ef/core/querying/related-data

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
    .UseLazyLoadingProxies()
    .UseSqlServer(myConnectionString);

This should solve the problem.

EF Core does not support lazy loading. You will need to eager load the objects using .Include

The reason it worked when you called the Blogs first, is that the object was available in the context cache and hence it was able to populate the Blog object successfully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM