Creating Relationships Between Entities in gRPC Using Proto Files

Kamyab Faghih 60 Reputation points
2024-11-03T13:23:00.6666667+00:00

Hello everyone, I have just started working with ASP.NET Core gRPC. I have a question: I have several proto files, and one of these files references another proto file. In this case, I want to use messages from the referenced file as fields in a message (essentially, these two entities have a one-to-many relationship). Could you please guide me on how to implement this?

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,605 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jerry Fu - MSFT 741 Reputation points Microsoft Vendor
    2024-11-05T13:42:37.07+00:00

    Hi Kamyab Faghih,

    You could use repeated to define one-to-many field in proto files. Such as following:

    Protos/Service1.proto

    syntax = "proto3";
    option csharp_namespace = "WebApplication310.Protos";
    service Service1 {
      rpc GetOrder(OrderRequest) returns (Order);
    }
    message OrderRequest{
        int32 orderId =1;
    }
    message Order {
      int32 orderId = 1;
      repeated Item items=2;
    }
    message Item {
        int32 id = 1;
        string name = 2;
    }
    
    
    

    Then you could make use the Order entity like following:

    MyService.cs

        public class MyService : WebApplication310.Protos.Service1.Service1Base
        {
            public override Task<Order> GetOrder(OrderRequest request, ServerCallContext context)
            {
                var items = new List<Item>
                {
                    new Item { Id = 1, Name = "Apple" },
                    new Item { Id = 2, Name = "Orange" }
                };
    
                return Task.FromResult(new Order
                {
                    OrderId = request.OrderId,
                    Items = { items }
                });
            }
        }
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".  Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.