Search code examples
c#databaseentity-frameworkef-code-first

EF Core: Return all items that have item with property==x in their collection


thanks for advance for any help. I'm starting to learn EF Core, suppose I have these 2 classes:

 public class Post

{
    public Guid Id { get; set; } = Guid.NewGuid();

    public String Name { get; set; }

    public ICollection<Tag> Tags { get; set; }

}



public class Tag

{

    public Guid TagId { get; set; } = Guid.NewGuid();

    public String Name { get; set; }

    public Guid PostId { get; set; }

    public Post Post { get; set; }

}

How do I form a query that returns all the posts that have a tag with the name "X"?


Solution

  • Word of caution, when doing string compares you can run into some issues with case sensitivity. I usually just lowercase everything when comparing if I don't need to have case sensitivity on in cases like pass codes or something like that.

    var posts = await context.Posts
        .Where(p => p.Tags.Any(t => t.TagName.ToLower() == "tag name"))
        .ToListAsync()