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

Display Wall メソッド (ここでは、ユーザー リストを更新する必要があります)-

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

1 に答える 1

3

user.MyWall.Add(reader["WallText"])読み取りループ内はどうですか?ただし、投稿を追加する前に、投稿が既にリストにあるかどうかを確認することをお勧めします。

于 2013-10-29T16:08:22.063 に答える