linq 实体框架中的条件Include()()

gupuwyp2  于 2022-12-15  发布在  其他
关注(0)|答案(8)|浏览(250)

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

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

附件可以由作者(类型Author)或参与者(类型Contributor)上传。我想要做的是,只获取附件所有者类型为Author的附件。
我知道这是行不通的,并给出一个错误:

.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; }
}
q1qsirdb

q1qsirdb1#

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

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

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

mu0hgdu0

mu0hgdu02#

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

px9o7tmv3#

Attachments导航属性中删除virtual关键字以防止延迟加载:
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()
j13ufse2

j13ufse24#

可以使用扩展方法Include2()this implementation,之后可以调用:

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

上面的代码只包括Attachment.OwnerId == 1的附件。

0md85ypi

0md85ypi5#

试试这个

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();
6qftjkof

6qftjkof6#

网芯用
https://learn.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();

它对SQL进行2次查询。

cbwuti44

cbwuti447#

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

2wnc66cl

2wnc66cl8#

假设“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)

相关问题