Storing C# data structure into a SQL database

前端 未结 7 2048
半阙折子戏
半阙折子戏 2021-02-01 10:02

I am new to the world of ASP.NET and SQL server, so please pardon my ignorance ...

If I have a data structure in C# (for e.g. let\'s just say, a vector that stores some

7条回答
  •  失恋的感觉
    2021-02-01 10:30

    Here's another more general approach for generic lists. Note, the actual type stored in the list must also be serializable

    using System.Runtime.Serialization.Formatters.Binary;
    using System.IO;
    using System.Data.SqlClient;
    using System.Runtime.Serialization;
    
    public byte[] SerializeList(List list)
    {
    
        MemoryStream ms = new MemoryStream();
    
        BinaryFormatter bf = new BinaryFormatter();
    
        bf.Serialize(ms, list);
    
        ms.Position = 0;
    
        byte[] serializedList = new byte[ms.Length];
    
        ms.Read(serializedList, 0, (int)ms.Length);
    
        ms.Close();
    
        return serializedList; 
    
    } 
    
    public List DeserializeList(byte[] data)
    {
        try
        {
            MemoryStream ms = new MemoryStream();
    
            ms.Write(data, 0, data.Length);
    
            ms.Position = 0;
    
            BinaryFormatter bf = new BinaryFormatter();
    
            List list = bf.Deserialize(ms) as List;
    
            return list;
        }
        catch (SerializationException ex)
        {
            // Handle deserialization problems here.
            Debug.WriteLine(ex.ToString());
    
            return null;
        }
    
    }
    

    Then in client code:

    List stringList = new List() { "January", "February", "March" };
    
    byte[] data = SerializeList(stringList);
    

    One basic way of storing/retrieving this array of bytes could be to use simple SQLClient objects:

    SqlParameter param = new SqlParameter("columnName", SqlDbType.Binary, data.Length);
    param.Value = data; 
    
    etc...
    

提交回复
热议问题