Alberto Chiesa
Alberto Chiesa

Reputation: 7360

Protobuf - Replacing a generic Collection

I'm using C# in .Net Core 3.1. I have a class, used in existing projects / other APIs:

/// <summary>Class representing a Result Set (data coming from a result page,
/// plus the total count of the records coming from all the resulting pages) </summary>
/// <typeparam name="T">The class type of the result set</typeparam>
public class PagedResult<T>
{
    /// <summary> Total number of rows in the result set </summary>
    public long TotalRows { get; set; }

    /// <summary> IList containing the data of the requested page's result set  </summary>
    public IList<T> PageData { get; set; } = new List<T>();
}

I use this as the return type of many messages (basically every paged query).

How do I replace something like this in gRPC / Protobuf?

I can think of something along the lines of:

message PagedResult
{
  int32 total_rows = 1;
  repeated google.protobuf.Any page_data = 2;
}

But this will require me to treat every single result as different. The alternative is to create a new message for each page_data type:

message MyEntityPagedResult
{
  int32 total_rows = 1;
  repeated MyEntity page_data = 2;
}

I know that protobuf does not support inheritance, but is there a way to manage this kind of response without inserting a lot of boilerplate in the proto? Any advice?

Thanks!

Upvotes: 3

Views: 703

Answers (1)

Eyup Can ARSLAN
Eyup Can ARSLAN

Reputation: 752

enter image description here


May you can try to use Any keyword in your shell protobuf like this

message MyEntityPagedResult
{
  int32 total_rows = 1;
  any page_data = 2;
}

And your C# Client and Server side you can change this Any type like this

// Read Person message from detail.
if (status.page_data.Is(__YourClassType__))
{
    var person = status.page_data.Unpack<__YourClassType__>();
    ...
}

Note: At this solution, YourClassType have to define in proto as message class. this can In my opinion there isnt any way to achive like type in proto file :/

Edit: This link also can give detail information about your problem. :) Have a good coding :D

Upvotes: 2

Related Questions