Search code examples
c#asp.net-mvclistfiltermodel

ASP.NET MVC : how to get list of an items from other model by Id


I have two models: Picture.cs

    public class Picture
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public string Link { get; set; }
}

And User.cs

    public class User
{
    public int Id { get; set; }
    public virtual List<Picture> Pictures { get; set; }
}

In a List<Picture>, I want to get all pictures with UserId = User Id, but instead of it I get all pictures in the database that I have.


Solution

  • Given you already have a List<Picture> allPictures, you would simply use linq to filter the listed based on userid:

    List<Picture> picturesForUser = allPictures.Where(x => x.UserId == someUserId).ToList()

    or you can query them directly from the database as @Javi suggested:

    List<Picture> picturesForUser = yourDbContext.Pictures.Where(p => p.UserId == someUserId).ToList();