1

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.

1 Answer 1

4

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();
Sign up to request clarification or add additional context in comments.

Comments

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.