Conditional Include() in Entity Framework

前端 未结 8 1928
暗喜
暗喜 2020-11-28 09:03

I have seen a few answers to similar questions, however I cannot seem to work out how to apply the answer to my issue.

var allposts = _context.Posts
                 


        
相关标签:
8条回答
  • 2020-11-28 09:27

    For net core

    https://docs.microsoft.com/ru-ru/ef/core/querying/related-data/explicit

    var allposts = _context.Posts
            .Include(p => p.Comments)
            .Include(a => a.PostAuthor)
            .Where(t => t.PostAuthor.Id == postAuthorId).ToList();
    
    _context.Entry(allposts)
            .Collection(e => e.Attachments)
            .Query()
            .Where(e=> e.Owner is Author)
            .Load();
    

    it makes 2 query to sql.

    0 讨论(0)
  • 2020-11-28 09:30

    Remove the virtual keyword from your Attachments navigation property to prevent lazy loading:

    public ICollection<Attachment> Attachments { get; set; }

    First method: Issue two separate queries: one for the Posts, one for the Attachments, and let relationship fix-up do the rest:

    List<Post> postsWithAuthoredAttachments = _context.Posts
        .Include(p => p.Comments) 
        .Include(p => p.PostAuthor)
        .Where(p => p.PostAuthor.Id == postAuthorId)
        .ToList();
    
    List<Attachment> filteredAttachments = _context.Attachments
        .Where(a => a.Post.PostAuthor.Id == postAuthorId)
        .Where(a => a.Owner is Author)
        .ToList()
    

    Relationship fixup means that you can access these filtered Attachments via a Post's navigation property

    Second method: one query to the database followed by an in-memory query:

    var query = _context.Posts
        .Include(p => p.Comments) 
        .Include(p => p.PostAuthor)
        .Where(p => p.PostAuthor.Id == postAuthorId)
        .Select(p => new 
            {
                Post = p,
                AuthoredAttachments = p.Attachments
                    Where(a => a.Owner is Author)
            }
        );
    

    I would just use the anonymous type here

    var postsWithAuthoredAttachments = query.ToList()
    

    or I would create a ViewModel class to avoid the anonymous type:

    List<MyDisplayTemplate> postsWithAuthoredAttachments = 
         //query as above but use new PostWithAuthoredAttachments in the Select
    

    Or, if you really want to unwrap the Posts:

    List<Post> postsWithAuthoredAttachments = query.//you could "inline" this variable
        .AsEnumerable() //force the database query to run as is - pulling data into memory
        .Select(p => p) //unwrap the Posts from the in-memory results
        .ToList()
    
    0 讨论(0)
提交回复
热议问题