Ignore Non Serialized property in BinaryFormatter Serialization

眉间皱痕 提交于 2020-01-01 05:39:26

问题


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; }
}

回答1:


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.



来源:https://stackoverflow.com/questions/33489930/ignore-non-serialized-property-in-binaryformatter-serialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!