loveforfire33
loveforfire33

Reputation: 1110

Query DB With A List

im trying to learn mvc by making a simple social network. Bit suck here. Im trying to create 2 db querys.

The first to get a list of all the people that the current user is following.

The second to get a list of all the posts of those users. Been trying this all day. Could someone help me out please!

string id = //username of user we are finding friends for

//get all the people user is following
List<Friend> friendList = db.Freinds.Where(x => x.username == id).ToList();

//get all posts for those people
List<Post> postList = db.Posts.Where(x => friendList.Contains(x.Username)).ToList();

My Models:

public class Post
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Int32 PostID { get; set; }

        public string Username { get; set; }

        public string Wallname { get; set; }

        public DateTime PostDateTime { get; set; }

        [Required(ErrorMessage = "{0} Is Required")]
        [Display(Name = "Post Content")]
        public String PostContent { get; set; }

        public virtual List<Comment> Comments { get; set; }
    }


   public class Friend
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int friendID { get; set; }

        public string username { get; set; }

        public string following {get;set;}
    }

Thanks in advance.

Upvotes: 1

Views: 73

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239270

You're almost there; you just have a bit of a logic problem. You're asking for posts where friendsLists contains the post's Username. That will never match because friendsLists is a list of Friend objects, whereas Username is a string: String != Friend, so no matches.

What you really need is to first condense friendsList into a list of strings, namely just the Username property of each Friend instance:

var friendUsernames = friendsList.Select(m => m.Username);

List<Post> postList = db.Posts.Where(x => friendUsernames.Contains(x.Username)).ToList();

Upvotes: 4

Related Questions