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

时间:2015-09-24 00:14:19

标签: c# entity-framework linq linq-to-entities

我已经看到了类似问题的一些答案,但我似乎无法解决如何将答案应用于我的问题。

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

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

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

.Include(s=>aa.Attachments.Where(o=>o.Owner is Author))

我已在此处阅读过滤投影

编辑 - 链接到文章: :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; }
}

9 个答案:

答案 0 :(得分:11)

从您发布的链接中我可以确认该技巧有效,但仅适用于一对多(或多对一)关系。在这种情况下,您的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();

答案 1 :(得分:4)

virtual导航属性中删除Attachments关键字以防止延迟加载:

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

第一种方法:发出两个单独的查询:一个用于帖子,一个用于附件,让关系修复完成剩下的工作:

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()

关系修正意味着您可以通过帖子的导航属性

访问这些已过滤的附件

第二种方法:对数据库进行一次查询,然后进行内存中查询:

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)
        }
    );

我只想在这里使用匿名类型

var postsWithAuthoredAttachments = query.ToList()

或者我会创建一个ViewModel类来避免使用匿名类型:

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

或者,如果你真的想打开帖子:

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()

答案 2 :(得分:3)

您可以使用this implementation扩展方法(例如)Include2()。之后,您可以致电:

_context.Posts.Include2(post => post.Attachments.Where(a => a.OwnerId == 1))

上面的代码仅包含Attachment.OwnerId == 1

的附件

答案 3 :(得分:2)

EF Core 5.0即将推出“过滤的包含”。

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

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

答案 4 :(得分:1)

尝试

var allposts = _context.Posts
        .Include(p => p.Comments)
        .Include(a => a.PostAuthor)
        .Where(t => t.PostAuthor.Id == postAuthorId).ToList();

_context.Attachments.Where(o=>o.Owner is Author).ToList();

答案 5 :(得分:0)

对于核心网

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

val divide: PartialFunction[Int, Int] = {
    case d: Int if d != 0 => 42 / d
}

它对sql进行2次查询。

答案 6 :(得分:0)

进行查询

{       
    var allposts = _context.Posts
        .Include(p => p.Comments)
        .Include(aa => aa.Attachments)
        .Include(a => a.PostAuthor)
        .AsNoTracking()
        .ToList();

    await allposts.ForEach((FilterByOwner));
}

private async void FilterByOwner(Post post)
{
    post.Attachments = post.Attachments.Where(o => o.Owner is Author);
}

答案 7 :(得分:-3)

Include()中的Lambda只能指向一个属性:

.Include(a => a.Attachments)
.Include(a => a.Attachments.Owner);

你的情况对我来说没有意义,因为Include()表示join而你要么做或不做。而不是有条件的。

你会如何在原始SQL中写这个?

为什么不呢:

context.Attachments
       .Where(a => a.Owner.Id == postAuthorId &&
                   a.Owner.Type == authorType);

答案 8 :(得分:-3)

假设“a”属于“YourType”类型,可以通过使用方法扩展来解决条件包含,例如

public static class QueryableExtensions
{
    public static IQueryable<T> ConditionalInclude<T>(this IQueryable<T> source, bool include) where T : YourType
    {
        if (include)
        {
            return source
                .Include(a => a.Attachments)
                .Include(a => a.Attachments.Owner));
        }

        return source;
    }
}

...然后就像使用它一样使用它。包括,例如

bool yourCondition;

.ConditionalInclude(yourCondition)