0

I need to get all posts where their images have an Approved of false. Here is my two Models, Post and Image models:

public class Post
{
   public Post()
   {
       Images = new List<Image>();
   }

   public int Id { get; set; }

   public ICollection<Image> Images { get; set; }

   // ....
}



public class Image
{
    public int Id { get; set; }
    public string FileName { get; set; }
    public bool Approved { get; set; } = false;

    public Post Post { get; set; }
    public int PostId { get; set; }
}

This is the query Im doing right now to get all the posts:

public IActionResult GetPosts()
{
  var posts = _context.Posts
      .Include(c => c.User)
      .Include(c => c.Images)
      .ToList();

  return Ok(posts);
}

I need to get all the posts where its images approved = false. I tried doing this in the post query, but got various errors:

//.Where(c => _context.Images.Select(b => b.PostId).Contains(c.Approved == false))
//.Include(c => c.Images.Where(b => b.Approved == false))

This is how the images table looks for reference:

My SQL Images Table

So in this example, I would need to get Post ID of 1 because one of its images is set to Approved = false. How would I do that in a query?

1 Answer 1

1

To get all posts that are not approved...

var posts = _context.Images
  .Where(i => i.Approved == false)
  .Select(i => i.Post)
  .ToList();

To get one post based on the ID...

var posts = _context.Posts
  .Include(c => c.User)
  .Include(c => c.Images)
  .Where(b => b.PostId == 1)
  .ToList();
Sign up to request clarification or add additional context in comments.

3 Comments

That query does not return any Posts because that where clause is accessing the Post Model Approved attribute instead of the Images Approved Attribute. I have approved columns in both Post and Images table. When I hover over c.Approved in Visual Studio, it shows "bool Post.Approved { get; set; }"
I edited the answer. I dont see where users is related so you will have to add that to the select. You can change the select to grab data from child tables into an Anonymous object if you need different fields. This is basic Lamda and you can find these answers with a quick google next time
Yes that works, I also added a Distinct() at the end to show post only once in table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.