Can I serialize an object if I didn't write the class used to instantiate that object?

Posted by Richard77 on Stack Overflow See other posts from Stack Overflow or by Richard77
Published on 2010-04-15T14:17:32Z Indexed on 2010/04/15 14:23 UTC
Read the original article Hit count: 345

Hello,

I've a simple class

[Serializable]
public class MyClass
{
  public String FirstName { get; set: }
  public String LastName { get; set: }

  //Bellow is what I would like to do
  //But, it's not working
  //I get an exception
  ContactDataContext db = new ContactDataContext();

  public void Save()
  {
   Contact contact = new Contact();
   contact.FirstName = FirstName;
   contact.LastName = LastName;

   db.Contacts.InsertOnSubmit(contact);
   db.SubmitChanges();
  }
}

I wanted to attach a Save method to the class so that I could call it on each object. When I introduced the above statement which contains ContactDataContext, I got the following error "In assembly ... PublicKeyToken=null' is not marked as serializable"

It's clear that the DataContext class is generated by the framework (). I checked and did not see where that class was marked serialize.

What can I do to overcome that? What's the rule when I'm not the author of a class? Just go ahead and mark the DataContext class as serializable, and pretend that everything will work?

Thanks for helping

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about linq-to-sql