如何在mysql和c#中的列表中选择多个子表记录?

时间:2016-12-11 07:49:55

标签: c# mysql

我在mysql中有两个表“user”和“user_media”。表格如下:

User:

id, name, phone, address
1, abc, 000000000, x lane, y city

user_media:

mid, user_id, media_url
j432, 1, http://.....sdfl.png
j84d, 1, http://.....snx8.png

我想在c#中访问数据:

string id;
string name;
string phone;
string address;
List<string> mediaImages;

如何以这种方式访问​​数据。

1 个答案:

答案 0 :(得分:0)

INNER JOIN返回第一个表中的所有行,其中第二个表中的所有行都与ON条件匹配。来自第一个表的匹配行被复制以容纳来自第二个表的数据。您的代码应该从Media表中插入所需列表中的数据。

// This list will store all the records retrieved
List<User> usersList = new List<User>();

string cmdText = "SELECT * FROM user INNER JOIN user_media ON user.id = user_media.user_id";
using(MySqlConnection con = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, con))
{
    // Starting values
    int currentUser = -1;
    User usr = null;

    con.Open();
    using(MySqlDataReader reader = cmd.ExecuteReader())
    {
        // Loop over the results till the end
        while(reader.Read())
        {
             // If the current record is for a different user.....
             if(reader.GetInt32("id") != currentUser)
             {
                 // Create it
                 usr = new User();
                 // this should go in the constructor of User....
                 usr.MediaImages = new List<string>();

                 // Fill the field for the current user...
                 usr.id = reader.GetInt32("id");
                 usr.name = reader.GetString("name");
                 usr.phone = reader.GetString("phone");
                 usr.address = reader.GetString("address");

                 // Add the retrieved user to the whole list
                 userList.Add(usr);

                 // Prevent adding other elements to the list for the same user....
                 currentUser = usr.ID;
             }

             // For the current user add only the url info 
             usr.MediaImages.Add(reader.GetString("media_url"));
        }
    }
}

正如您所看到的,这是很多样板代码....如果您真的想从这些细节中抽象出代码,我建议您查看可以为您执行此操作的ORM(对象关系映射器)工具。