How to serialize circular referenced ef poco class using protobuf-net

Viewed 92

I'm using marc gravell's protobuf-net and ef core in my project.

long story short, I'm using Inverseproperty attribute on my POCO class which causes a circular reference when I fetch results from database which causes me trauble when I try to serialize data using protobuf net.

I'm currenyl serializing data with Jsonconvert by setting ReferenceLoopHandling = ReferenceLoopHandling.Ignore and returning a json string to the client to keep the app in a working state but do not want to use this method as it doesnot make any sense.

I would like to know if it is possible to either prevent EF core generating circular reference when using Inverseproperty attribute or if protobuf-net has an ignore referenceloop handling feature when serializing data..

a simplified version of my poco class is like this:

[ProtoContract]
[Table("CATEGORIES_M")]
public class CATEGORIES_M
{
    public CATEGORIES_M()
    {
        CATEGORIES_M_COLLECTION = new HashSet<CATEGORIES_M>();
        //Product = new HashSet<Product>();
        CM_DATE = DateTime.Now;
    }

    [Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [ProtoMember(1)]
    public int CM_ROWID { get; set; }

    [ProtoMember(2)]
    public string CM_NAME { get; set; }

    [ProtoMember(3)]
    public int? CM_PARENT_REFNO { get; set; }

    [ProtoMember(4)]
    [ForeignKey(nameof(CM_PARENT_REFNO))]
    [InverseProperty(nameof(CATEGORIES_M_COLLECTION))]
    public  CATEGORIES_M CATEGORIES_M_PARENT { get; set; }

    [ProtoMember(5)]
    [InverseProperty(nameof(CATEGORIES_M_PARENT))]
    public  ICollection<CATEGORIES_M> CATEGORIES_M_COLLECTION { get; set; }  
}

any help is appreciated

1 Answers

Protobuf-net does not have good support for this scenario. V2 has some limited reference tracking capabilities, but these are deprecated in V3 because it caused more problems than it solved. My suggestions, as the library author:

  1. serialize a simple tree model, and build your real model afterwards from it, or
  2. use a different tool
Related