【问题标题】:LINQ Include condition not applyingLINQ 包含条件不适用
【发布时间】:2015-02-15 12:29:58
【问题描述】:

我有以下两个实体:

public class Artist
{
    public int Id { get; set; }
    public string FName { get; set; }
    public string LName { get; set; }
    public string UrlFriendly { get; set; }
    public string ImgURL { get; set; }
    public bool Verified { get; set; }
    // relations
    public virtual ICollection<Painting> Paintings { get; set; } 
}

还有:

public class Painting
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string ImgUrl { get; set; }
    public bool Verified { get; set; }
    // relations
    public int ArtistId { get; set; }
    public virtual Artist Artist { get; set; }
}

然后在我的数据访问层,我有以下 LINQ:

public Artist GetArtistByUrlFriendly(string urlFriendly)
{
    return _context
            .Artists
            .Include("Paintings")
            .Where(a => a.Verified == true && a.Paintings.Any(p => p.Verified == true))
            .FirstOrDefault(a => a.UrlFriendly == urlFriendly);
}

所以我想要一个特定的艺术家和他的画,但这个艺术家必须经过验证,他的画也必须经过验证。上面那个LINQ应该不行吧?

但事实并非如此!它也会返回未经验证的画作!知道为什么会这样吗?

【问题讨论】:

    标签: c# linq ef-code-first


    【解决方案1】:

    您的查询仅检查艺术家至少有一幅经过验证的画作。如果他们这样做了,那么Include("Paintings") 将加载所有他们的画(验证与否)。

    您的意思是您只想退回给定艺术家的经过验证的画作吗?在这种情况下,您可以发出单独的查询来仅填充他们经过验证的画作。

    public Artist GetArtistByUrlFriendly(string urlFriendly)
    {
        var artist = _context.Artists.FirstOrDefault(a => 
            a.UrlFriendly == urlFriendly && a.Verified);
    
        if (artist != null)
            artist.Paintings = _context.Paintings.Where(p => 
                p.ArtistId == a.Id && p.Verified).ToList();
    
        return artist;
    }
    

    编辑:如果Artist.Paintings 属性是只读的,您可以改用以下调用(改编自this answer 和this blog post):

        if (artist != null)
            context.Entry(artist)
                   .Collection(a => a.Paintings)
                   .Query()
                   .Where(p => p.Verified)
                   .Load();
    

    【讨论】:

    • 是的,这正是我所追求的。有没有办法在单个 LINQ 查询中做到这一点?
    • 是的,但它变得笨拙:您要么需要调用 Artist() 构造函数并在 Select 中初始化其所有属性,要么使用匿名类型。
    • 谢谢,我喜欢可读性,所以我会这样做。谢谢你:)
    猜你喜欢
    • 2016-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多