How to serialize SqlParameter ?

M

Marcin

hi, I would like to ask how to serialize class with members like
SqlParameter. I try to use BinaryFormatter.

[Serializable]
public class Example_Class
{

public SqlParameter sqlParam;

public Example_Class()
{
sqlParam = new SqlParameter("@Data", SqlDbType.VarChar);
}
}

class App
{
[STAThread]
static void Main()
{
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);

try
{
// Construct a BinaryFormatter and use it
// to serialize the data to the stream.
BinaryFormatter formatter = new

Example_Class dod = new Example_Class();
// Serialize the array elements.
formatter.Serialize(fs, dod);

// Deserialize the array elements.
fs.Position = 0;
Example_Class dod2 = (Example_Class) formatter.Deserialize(fs);


Console.WriteLine("Do both class refer to the same object? "
+ (dod.sqlParam == dod2.sqlParam));
Console.ReadLine();

}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
Console.ReadLine();
throw;
}
finally
{
fs.Close();
}
}

and error is :

"The type System.Data.SqlClient.SqlParameter in Assembly System.Data,
Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 is
not marked as serializable."

but I know that's possible. What I do wrong ?
How do I have to implement this?

Thanks,
Marcin
 
N

Nicholas Paldino [.NET/C# MVP]

Marcin,

You would have to mark the field with the SqlParameter as
NonSerializable (with the attribute). Then, you can implement the
IDerializationCallback interface to be notified when deserialization is
complete, so that you can re-initialize it.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top