我有以下两个实体:
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不应该这样做吗?
但它没有!它返回的画作也未经过验证!知道为什么会这样吗?
答案 0 :(得分: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):< / p>
if (artist != null)
context.Entry(artist)
.Collection(a => a.Paintings)
.Query()
.Where(p => p.Verified)
.Load();