LINQ 包含条件不适用

LINQ Include condition not applying

我有以下两个实体:

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应该做不?

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

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

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

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

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

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