简体   繁体   中英

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"?

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

You can do like this:

var postsWithTagX = await context.Post
.Where(p => p.Tags.Any(t => t.TagId == "The Tag Id you want"))
.ToListAsync()

Edit:

You can get it from include.

var tag = await context.Tag
.Include(x => x.Post)
.FirstOrDefaultAsync(t => t.TagId == "The Tag Id you want");

var posts = tag.Posts.Tolist()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM