Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

.net - Serialize C# class directly to SQL server?

can anyone suggest the best way to serialize data (a class actually) to a DB?

I am using SQL server 2008 but i presume i need to serialize the class to a string / or other data type before storing in the database?

I presume that this field needs to be text or binary??

Does SQL server 2008 (or .net 3.5) support serializing directly tothe database ??

Any help really appreciated

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can xml serialize the class into an xml field. We use this all the time for exception logging in an ETL.

Using the XmlSerializer you may want a helper method somewhere which serializes the class to a string...

public static string SerializeToXml<T>(T value)
{
    StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    serializer.Serialize(writer, value);
    return writer.ToString();
}

Then just put the string into the db like any other.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...