S
S
Sneiksus2019-04-13 10:14:07
SQL
Sneiksus, 2019-04-13 10:14:07

Is it possible to store a List or a 2D array in a DB?

MS SQL database. I am using Entity Framework. How can I save an array or a sheet there? Does SQL have some type? Or can it be serialized? Or do you need an additional table? Give examples in code, please.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Ascar, 2019-04-14
@Sneiksus

If you just put an array or other object in a field, then serialize:

table.arrayField = JsonConvert.SerializeObject(new string[] { "123", "qwe", "asd" });

//deserialize
var array = JsonConvert.DeserializeObject<string[]>(table.arrayField);

S
Sergey Gornostaev, 2019-04-13
@sergey-gornostaev

Maybe. I didn’t specifically use the Entity Framework, but in other ORMs and relational databases in general, this is implemented by relationships : the list items are stored as rows of the same or another table that have a foreign key field on the row that stores the data of the original entity.

C
CHolfield, 2019-04-13
@CHolfield

Anything can be serialized

using System.Text;
using System.Xml;
using System.Xml.Serialization;

private class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding { get { return Encoding.UTF8; } }
    }

var xs = new XmlSerializer(ObjectName.GetType());
                            var xml = new Utf8StringWriter();
                            xs.Serialize(xml, ObjectName);//xml.ToString() - тут строка содержимого в xml формате, оч удобно

And back
private static T Deserialize<T>(string xml)
    {
        var xs = new XmlSerializer(typeof(T));
        return (T)xs.Deserialize(new StringReader(xml));
    }

ObjectNameType ObjectName = Deserialize<ObjectNameType>(plaintext);//та самая строка xml содержимого на входе, объект нужного типа на выходе

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question