将Arraylist数据添加到数据库

时间:2015-12-06 11:45:59

标签: c# database variables arraylist

我有一些变量是Arraylists,有些是字符串。我有类方法,它使用继承从另一个类获取变量并将它们添加到database.Here是我的代码:

System.Data.SqlClient.SqlConnection sqlConnection1 = new System.Data.SqlClient.SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Darius\Documents\Visual Studio 2013\Projects\FilmuBiblioteka\FilmuBiblioteka\duombaze.mdf");

            sqlConnection1.Open();
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.CommandText = "INSERT filmai (Id, Pavadinimas, Metai, trukme, salis, kalba, reitingas, zanras, aktoriai, link, plot, rezisieriai) VALUES (@Id, @Title, @Year, @Runtime, @Countries, @Languages, @Rating, @Genres, @Cast, @ImdbURL, @Plot, @Directors)";
            cmd.Parameters.AddWithValue("Id", Id);
            cmd.Parameters.AddWithValue("Title", Title);
            cmd.Parameters.AddWithValue("Year", Year);
            cmd.Parameters.AddWithValue("Runtime", Runtime);
            cmd.Parameters.AddWithValue("Countries", Countries); *
            cmd.Parameters.AddWithValue("Languages", Languages); *
            cmd.Parameters.AddWithValue("Rating", Rating);
            cmd.Parameters.AddWithValue("Genres", Genres); *
            cmd.Parameters.AddWithValue("Cast", Cast); *
            cmd.Parameters.AddWithValue("ImdbURL", ImdbURL);
            cmd.Parameters.AddWithValue("Plot", Plot);
            cmd.Parameters.AddWithValue("Directors", Directors); *
            cmd.Connection = sqlConnection1;
            cmd.ExecuteNonQuery();
            sqlConnection1.Close();

符号 - *表示这些变量是arraylists。所以,我收到了这个错误:No mapping exists from object type System.Collections.ArrayList to a known managed provider native type.

如何解决,所以可以将所有内容添加到数据库中?

1 个答案:

答案 0 :(得分:1)

如果您的数据库不支持数组类型,并且您不想将您的Contries,Languages等提取到单独的引用表中,我想您还可以将ArrayList展平为一个字符串,如下所示:

    // Convert the ArrayList to a string
    string separator = "|"; // Any string that doesn't collide with content
    string arrayListAsString = String.Join(separator, Contries.ToArray());

然后将字符串保存在数据库中。从数据库中读取字符串时,您可能希望将其转换回ArrayList:

    // Convert the string back to an ArrayList
    ArrayList list = new ArrayList();
    list.AddRange(arrayListAsString.Split(new string[]{separator}, StringSplitOptions.RemoveEmptyEntries));