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
The problem is that the
dbfield gets serialized, while clearly it doesn’t need to be serialized (it’s instantiated once the object is created).Therefore, you should decorate it with the
NonSerializedattribute:[Update]
To make sure the
dbfield is accesable after object initialization, you should use a lazy loading property and use this property instead of the field:[Update2]
You can serialize most objects, as long as it has a public parameterless constructor (or no constructor at all) and no properties/fields that cannot be serialized but require serializing. If the class itself is not marked as
[Serializable], then you can do this yourself using a partial class. If the class has properties/fields that cannot be serialized, then you might achieve this by inheriting the class and overriding these properties/fields to decorate them as[NonSerialized].