使用列表查询数据库

时间:2013-11-22 18:47:15

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我试图通过建立一个简单的社交网络来学习mvc。有点吮吸这里。我试图创建2 db查询。

第一个获取当前用户关注的所有人的列表。

第二个获取这些用户的所有帖子的列表。一直在尝试这一天。请有人帮帮我!

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

我的模特:

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;}
    }

提前致谢。

1 个答案:

答案 0 :(得分:4)

你快到了;你只是有一点逻辑问题。您要求friendsLists包含帖子Username的帖子。这永远不会匹配,因为friendsListsFriend个对象的列表,而Username是一个字符串:String!= Friend,所以没有匹配。

您真正需要的是首先将friendsList压缩到字符串列表中,即只是每个Username实例的Friend属性:

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

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