I have a class called User
and it is [Serializable]
and inherited from base class IdentityUser
an Entity Framework class and Non Serializab
BinaryFormatter
serializes the public and private fields of a object -- not the properties. For an auto-implemented property the secret backing field is what is actually serialized.
Normally, if you do not want a field to be serialized, you can apply the [NonSerialized] attribute, and BinaryFormatter
will skip it. In c# 7.3 and later, it's possible to do this to the secret backing field of an auto-implemented property by using a field-targeted attribute:
[field: NonSerialized]
public virtual User Guest { set; get; }
See: Auto-Implemented Property Field-Targeted Attributes and What's new in C# 7.3.
Prior to c# 7.3 there is no way to apply an attribute to the backing field of an auto-implemented property. Thus you need to make the backing field be explicit:
[Serializable]
public class Booking
{
[ForeignKey("Guest")]
public string GuestId { set; get; }
[NonSerialized]
User guest;
public virtual User Guest { set { guest = value; } get { return guest; } }
}
Incidentally, if you need to serialize some of the information in User
, you could consider implementing ISerializable, or replacing instances of User
with serialization surrogates.