Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

EF-core Find method doesn't include other entities

+1
−0

(Full code available for cloning here)

I've run into some odd behavior of EF-core's Find method. It seems like the returned entity doesn't include the rest of the data.

MWE

Models
using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public string DbPath { get; }

    public BloggingContext()
    {
        var folder = Environment.SpecialFolder.LocalApplicationData;
        var path = Environment.GetFolderPath(folder);
        DbPath = System.IO.Path.Join(path, "blogging.db");
    }

    // The following configures EF to create a Sqlite database file in the
    // special "local" folder for your platform.
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; } = new();
}

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; }
}
int id;

Console.WriteLine("Setting up database:");
using (var db = new BloggingContext())
{
    Console.WriteLine($" - Database path: {db.DbPath}.");
    Console.WriteLine(" - Adding blog: http://blogs.msdn.com/adonet");
    var blog = new Blog { Url = "http://blogs.msdn.com/adonet" };
    db.Add(blog);
    db.SaveChanges();
    id = blog.BlogId;
}

Console.WriteLine($"Blog Id: {id}");

Console.WriteLine("Adding post");
using (var db = new BloggingContext())
{
    var blog = db.Blogs.Find(id);
    blog.Posts.Add(new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
    db.SaveChanges();
    Console.WriteLine($" - Number of Posts: {blog.Posts.Count()}");
}

Console.WriteLine($"Test: Finding blog with id: {id}");

using (var db = new BloggingContext())
{
    var blog = db.Blogs.Find(id);
    Console.WriteLine($" - Found blog: {blog.Url}");
    Console.WriteLine($" - Number of Posts: {blog.Posts.Count()}");
}

Console.WriteLine("Delete the blog");
using (var db = new BloggingContext())
{
    var blog = db.Blogs.Find(id);
    db.Remove(blog);
    db.SaveChanges();
}

Result

Setting up database:
 - Database path: C:\Users\[redacted]\AppData\Local\blogging.db.
 - Adding blog: http://blogs.msdn.com/adonet
Blog Id: 15
Adding post
 - Number of Posts: 1
Test: Finding blog with id: 15
 - Found blog: http://blogs.msdn.com/adonet
 - Number of Posts: 0
Delete the blog

Note: The 15 is just because I've run this a couple of times and it auto-incremented.

As you can see, it says that there are 0 posts in the blog returned by the Find method, even though I added one before.

I set a breakpoint before the blog deletion cleanup code and checked with a database viewer and the Post is indeed stored into the database with the correct Blog id.

I'm probably missing something obvious, but why doesn't it return the posts that I added before? And how do I get it to do so? Is there some configuration somewhere that manages this?

History
Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

0 comment threads

1 answer

+2
−0

What you want would be called DbSet<>.Find() combined with eager loading of the related entities. According to the docs, eager loading is not mentioned and its sole purpose is to easily get an entity based on its type and keys:

Finds an entity with the given primary key values. If an entity with the given primary key values is being tracked by the context, then it is returned immediately without making a request to the database. Otherwise, a query is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found, then null is returned.

In order to get an entity and its related entities, you can rely on a LINQ filter function + Include:

var blog = db.Blogs
    .Include(b => b.Posts)
    .FirstOrDefault(b => b.Id == id);

This will generate a query to fetch data for both the blog with and its associated posts (eager loading of the posts).

Note: For scenarios where performance is important, you can only fetch the required columns. Example:

var blogInfo = db.Blogs
    .Select(b => new 
        { 
            BlogId = b.BlogId, // explicit property name
            BlogUrl = b.Url,
            PostData = b.Posts.Select(p => new { p.Id, p.Title })
        }
    .FirstOrDefault(b => b.BlogId == id);

Of course, a DTO can be used instead of anonymous types. The interesting part is that EF Core (5+) figures out automatically that Posts columns are required and no explicit Include() is required.

History
Why does this post require moderator attention?
You might want to add some details to your flag.

0 comment threads

Sign up to answer this question »