实体框架中的条件包含()

gra*_*son 18 c# linq linq-to-entities entity-framework

我已经看到了类似问题的一些答案,但我似乎无法弄清楚如何将答案应用于我的问题.

var allposts = _context.Posts
            .Include(p => p.Comments)
            .Include(aa => aa.Attachments)
            .Include(a => a.PostAuthor)
            .Where(t => t.PostAuthor.Id == postAuthorId).ToList();
Run Code Online (Sandbox Code Playgroud)

附件可以由作者(类型作者)或贡献者(类型贡献者)上传.我想要做的是,只获取附件所有者属于作者类型的附件.

我知道这不起作用并给出错误:

.Include(s=>aa.Attachments.Where(o=>o.Owner is Author))
Run Code Online (Sandbox Code Playgroud)

我在这里读过Filtered Projection

编辑 - 链接到文章:: http://blogs.msdn.com/b/alexj/archive/2009/10/13/tip-37-how-to-do-a-conditional-include.aspx ,

但我无法理解它.

我不想在最后的where子句中包含过滤器,因为我想要所有帖子,但我只想检索属于作者的那些帖子的附件.

编辑2: - 请求发布模式

public abstract class Post : IPostable
{

    [Key]
    public int Id { get; set; }

    [Required]
    public DateTime PublishDate { get; set; }

    [Required]
    public String Title { get; set; }

    [Required]
    public String Description { get; set; }

    public Person PostAuthor { get; set; }
    public virtual ICollection<Attachment> Attachments { get; set; }
    public List<Comment> Comments { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

viv*_*una 21

EF Core 5.0 即将推出 Filtered Include。

var blogs = context.Blogs
    .Include(e => e.Posts.Where(p => p.Title.Contains("Cheese")))
    .ToList();
Run Code Online (Sandbox Code Playgroud)

参考: https : //docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-5.0/whatsnew#filtered-include


Hop*_*ess 13

从您发布的链接我可以确认该技巧有效,但仅限于一对多(或多对一)关系.在这种情况下,你Post-Attachment应该是一对多的关系,所以它完全适用.这是您应该具有的查询:

//this should be disabled temporarily
_context.Configuration.LazyLoadingEnabled = false;
var allposts = _context.Posts.Where(t => t.PostAuthor.Id == postAuthorId)
                       .Select(e => new {
                           e,//for later projection
                           e.Comments,//cache Comments
                           //cache filtered Attachments
                           Attachments = e.Attachments.Where(a => a.Owner is Author),
                           e.PostAuthor//cache PostAuthor
                        })
                       .AsEnumerable()
                       .Select(e => e.e).ToList();
Run Code Online (Sandbox Code Playgroud)