how to save serializable object to database field
I'm using linq to sql and I have the need to save a few of our serializable objects to a field in our sql server database. I've defined the f开发者_开发百科ield as varbinary(MAX) but I'm not 100% sure that's correct. So, does anyone know how I can save an object to this field and then read it back? Thanks.
I think this depends on the format the objects are serialized in. For instance, if you are serializing out to xml then sql server (at least the latest version) supports an xml type. If you are indeed serializing out to binary, then sticking with binary is probably okay. Picking a db type that is similar to the type of the serialization will minimize a transformation bridging the db type to the object type.
I have gotten the object to serialize but I'm running into a problem getting the resulting xml saved. The object field is defined as xml so in linq to sql it's an xelement. I'm using the following code to serialize and get the xml string. But when I try to load the xml string to the xelement I get the "Illegal characters in path" error. However when I look at the generated xml I don't see any illegal characters. Here is the generated xml.
using (StringWriter sw = new StringWriter())
{
var x = new XmlSerializer(sessionObject.ObjectToStore.GetType());
x.Serialize(sw, sessionObject.ObjectToStore);
sessionRecord.sessionObject = XElement.Load(sw.ToString());
}
<?xml version="1.0" encoding="utf-16"?>
<SerializableJobSearch xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Keywords>electronics</Keywords>
<StateList />
<Radius>50</Radius>
<City />
<State />
<DisciplineIdList />
<IndustryIdList />
<Direct>false</Direct>
<TempHire>false</TempHire>
<Contract>false</Contract>
<PerHour>false</PerHour>
<PerYear>false</PerYear>
<DegreeLevel />
<IncludeJobsRequiringLess>false</IncludeJobsRequiringLess>
<AddedWithin>0</AddedWithin>
<OrderBy>Rank</OrderBy>
<OrderByRank>true</OrderByRank>
<resultsPerPage>50</resultsPerPage>
<NeedToMake />
</SerializableJobSearch>
精彩评论