Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore Non Serialized property in BinaryFormatter Serialization

I have a class called Userand it is [Serializable] and inherited from base class IdentityUser an Entity Framework class and Non Serializable.

I have a property in Booking class with type User and Booking class is Serializable I am trying to serialize the booking object using BinaryFormatter but I can't because of IdentityUser class and I get this error :

'Type 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser' in Assembly 'Microsoft.AspNet.Identity.EntityFramework, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable.'

Is there a way to ignore this property because I don't think there is away to make 'IdentityUser' as Serializable.

[Serializable]
public class User : IdentityUser
{
   public String FirstName { get; set; }
}

[Serializable]
public class Booking
{
   [ForeignKey("Guest")]
   public string GuestId { set; get; }
   public virtual User Guest { set; get; }
}
like image 649
kartal Avatar asked Nov 03 '15 01:11

kartal


1 Answers

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.

like image 128
dbc Avatar answered Oct 01 '22 15:10

dbc