我有一個名爲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();
}
感謝您的意見。我會試着這樣。是的,我想檢查是否已經存在或不是,但我會在更新後執行,截至目前,我允許用戶發佈重複的帖子。 – RahulD