2013-10-29 56 views
0

我有一个名为users的类型User类。用户类具有属性Id, Name, Location, List<string>MyWall,List<User> FriendList。有三个表格正在更新一个列表,列出另一个列表

User(UserId(PK),Name,Location), 
UserPost(PostID(PK),UserID(FK),WallText), 
UserFriends (UFId (PK),FriendID(FK),UserID(FK)) 

我首先通过询问名称和位置的详细信息来创建一个新用户。然后将这些详细信息插入到User table中,并在从数据库中读取这些详细信息后,我将它们存储到List<User> users = new List<User>()中,以便我可以进一步使用此列表进行显示,而不是从数据库中获取数据。

直到这里一切正常。现在创建用户后,我要求用户在墙上写帖子(可以是多个帖子),并将这些详细信息插入UserPost table。此外,我从数据库中获取与用户ID相对应的用户的帖子,现在我想要这些帖子在users列表中更新,但是当我添加墙帖(users.Add(user))时,整个用户详细信息将作为新的用户。 请告诉我如何更新我的users列表与墙贴,对应于现有的用户详细信息。

我的代码 -

在这里,我将不WallPost用户的详细信息,在用户列表 -

private void DisplayAllUsers() 
     { 
      connection.Open(); 
      SqlCommand command = new SqlCommand("DisplayUsers", connection); 
      using (SqlDataReader reader = command.ExecuteReader()) 
      { 
       command.CommandType = CommandType.StoredProcedure; 

       Console.WriteLine("Details of all the Users: "); 
       while (reader.Read()) 
       { 
        User user = new User() 
        { 
         ID = int.Parse(reader["UserId"].ToString()), 
         Name = reader["Name"].ToString(), 
         Location = reader["Location"].ToString() 
        }; 
        users.Add(user); 
        Console.WriteLine(); 
        Console.WriteLine("ID: " + user.ID + " Name: " + user.Name + " Location: " + user.Location); 
       } 
      } 

显示墙的方法(在这里我要更新用户列表) -

private void DisplayWall(User user) 
     { 
      OnDisplayDetails(user); 
      connection.Open(); 
      SqlCommand command = new SqlCommand("select WallText from UserPost where UserID='"+ user.ID +"'", connection); 
      using (SqlDataReader reader = command.ExecuteReader()) 
      { 
       while (reader.Read()) 
       { 
        Console.WriteLine(user.Name + " says " + reader["WallText"]); 
       } 
       int count = users.Count; 
//This LINQ doesn't work because MyWall is of type List<string> 
       //(from u in users 
       // where u.ID == user.ID 
       // select u).ToList().ForEach(u => u.MyWall = //reader["WallText"]); 
       //Here While Adding the User Details to the users list, it gets added with //all the details 
        users.Add(user); 
      } 
      connection.Close(); 
     } 

回答

3

user.MyWall.Add(reader["WallText"])怎么样在读取循环内?不过,您可能想要在添加之前检查该帖子是否已经在列表中。

+0

感谢您的意见。我会试着这样。是的,我想检查是否已经存在或不是,但我会在更新后执行,截至目前,我允许用户发布重复的帖子。 – RahulD

相关问题