简体   繁体   English

使用 DataTable 和 DataAdapter 在 SQL Server XML / string 列中存储序列化数据

[英]Storing serialized data in a SQL Server XML / string column with DataTable and DataAdapter

I wonder if someone can help me thru this scenario:我想知道是否有人可以通过这种情况帮助我:

In SQL Server, I have a column of type XML or string .在 SQL 服务器中,我有一个类型为XMLstring的列。 My application has a serializable data object which I want to store in that column.我的应用程序有一个可序列化的数据 object,我想将其存储在该列中。

The DataColumn in my DataTable has the type of this object. But when I try to update my database I get the exception我的DataTable中的DataColumn的类型为 object。但是当我尝试更新数据库时出现异常

No mapping exists from object type […] to a known managed provider native type不存在从 object 类型 […] 到已知托管提供程序本机类型的映射

This is actually clear, but is there a way to inject a converter / mapper doing this typed serialization and deserialization while Fill and Update using DataAdapter ?这实际上很清楚,但是有没有办法在使用DataAdapter FillUpdate时注入转换器/映射器来执行这种类型化的序列化和反序列化?

[Edit] [编辑] 这应该是数据流

Yes, I do that.是的,我这样做。 My column definition in the SQL Server table is:我在 SQL Server 表中的列定义是:

[FileData] [varchar](max) NOT NULL

The Dataset in my app is defined like this, a string:我的应用程序中的数据集是这样定义的,一个字符串:

在此处输入图像描述

An Exception一个例外

No mapping exists from object type […] to a known managed provider native type不存在从 object 类型 […] 到已知托管提供程序本机类型的映射

appears when you forget to serialize an object when working with an xml column.当您在使用 xml 列时忘记序列化 object 时出现。 Here is an example of the correct approach when working with xml type fields这是使用 xml 类型字段时正确方法的示例

    using (SqlConnection cnn = new SqlConnection(connectionString))
{
    string sql = "INSERT INTO Sale_T(SaleID, SaleInfo) values(@SaleId, @SaleInfo);";
    cnn.Open();
    using (SqlCommand cmd = new SqlCommand(sql, cnn))
    {
        Sale saleInfo = new Sale
        {
            Client = "Thomas",
            SaleDate = DateTime.Now,
            Items = new List<Product> {
                new Product { ProductName = "Apple", Price = 1.5 },
                new Product { ProductName = "Orange", Price = 0.8 } }
        };
        cmd.Parameters.AddWithValue("@SaleId", 2);
        // An attempt to directly assign an object leads to System.ArgumentException "No mapping exists from object type Sale to a known managed provider native type."
        // cmd.Parameters.AddWithValue("@SaleInfo", saleInfo);
        // you have to pre-serialize

        var Ser2String = (Sale si) =>  { 
            XmlSerializer mySerializer = new XmlSerializer(typeof(Sale));
            using (StringWriter stringWriter = new StringWriter())
            {
                mySerializer.Serialize(stringWriter, si);
                return stringWriter.ToString();
            }
        };

        string serSale = Ser2String(saleInfo);
        cmd.Parameters.AddWithValue("@SaleInfo", serSale);
        cmd.ExecuteNonQuery();
    }
}

OK, here's the continuation of the story, only now using好的,这是故事的延续,只是现在使用

void DataAdapterFillExample(){
using (SqlConnection con = new SqlConnection(connectionString))
{
    using (SqlCommand cmd = new SqlCommand("SELECT * FROM Sale_T", con))
    {
        cmd.CommandType = CommandType.Text;
        using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
        {
            using (DataTable dataTable = new DataTable())
            {
                dataAdapter.Fill(dataTable);
                foreach (DataRow row in dataTable.Rows)
                {
                    string saleID = row["SaleID"].ToString();
                    // here you can add desSerialization
                    string saleInfo = row["SaleInfo"].ToString();
                    Console.WriteLine($"{saleID} | {saleInfo}");
                }
            }
        }
    }
}

result:结果:

1 | 1 | Peter0001-01-01T00:00:00Apple1.5Orange0.8 2 | Peter0001-01-01T00:00:00Apple1.5Orange0.8 2 | Thomas2023-01-23T18:01:50.4545511+03:00Apple1.5Orange0.8 Thomas2023-01-23T18:01:50.4545511+03:00Apple1.5Orange0.8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM