efcore 预先加载和显示加载的使用

官网: https://learn.microsoft.com/zh-cn/ef/core/querying/related-data/eager
预先加载的使用: 
关联两张表查询
using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .Include(blog => blog.Owner)
        .ToList();
}
查询多层级关联
using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .ThenInclude(post => post.Author)
        .ThenInclude(author => author.Photo)
        .ToList();
}

显示加载的使用: 
DbContext.Entry(...) API 显式加载导航属性。

显示加载导航属性
using (var context = new BloggingContext())
{
    var blog = await context.Blogs
        .SingleAsync(b => b.BlogId == 1);

    await context.Entry(blog)
        .Collection(b => b.Posts)
        .LoadAsync();

    await context.Entry(blog)
        .Reference(b => b.Owner)
        .LoadAsync();
}

 

显示查询多层级关联
using (var context = new BloggingContext())
{
    var blog = await context.Blogs
        .SingleAsync(b => b.BlogId == 1);
await context.Entry(blog) .Collection(b => b.Posts)
     .Query()
     .Include(r => r.Books)
     .LoadAsync()
}

 

显示查询关联实体
using (var context = new BloggingContext())
{
    var blog = await context.Blogs
        .SingleAsync(b => b.BlogId == 1);

    var postCount = await context.Entry(blog)
        .Collection(b => b.Posts)
        .Query()
        .CountAsync();
}

 

筛选要加载到内存中的关联实体
using (var context = new BloggingContext())
{
    var blog = await context.Blogs
        .SingleAsync(b => b.BlogId == 1);

    var goodPosts = await context.Entry(blog)
        .Collection(b => b.Posts)
        .Query()
        .Where(p => p.Rating > 3)
        .ToListAsync();
}

 

posted @ 2025-03-16 20:09  龙卷风吹毁停车场  阅读(9)  评论(0)    收藏  举报