从EF实体到gRPC Protobuf消息的映射

时间:2019-04-13 14:31:19

标签: entity-framework automapper grpc

我已经开始尝试使用gRPC,并且希望能够使用自动映射器将数据库实体映射到protobuf消息。但是我不知道如何映射重复的字段。

我的消息定义如下:

message WorklistResponse {
    repeated WorklistMessage Worklists = 1;
}

message WorklistMessage {
    int32 WorklistId = 1;
    repeated CollectionWorkMessage Work = 2;
}

message CollectionWorkMessage {
    int32 WorkId = 1;
    string AddressComment = 2;
}

我正在尝试从一个看起来像这样的实体进行映射:

[Table("Worklist")]
public sealed class DbWorklist
{
    public DbWorklist()
    {
        Work = new HashSet<DbWork>();
    }

    [Key]
    public int WorklistId { get; set; }
    public ICollection<DbWork> Work { get; set; }
}

相关实体DbWork是DbCollectionWork的抽象基类,如下所示:

[Table("Work")]
public abstract class DbWork
{
    [Key]
    public int WorkId { get; set; }
    public int WorklistId { get; set; }

    [ForeignKey(nameof(WorklistId))]
    public DbWorklist Worklist { get; set; }
}

public sealed class DbCollectionWork : DbWork
{
    [StringLength(255)]
    public string AddressComment { get; set; }
}

我配置了两个映射:

cfg.CreateMap<DbWorklist, WorklistMessage>();
cfg.CreateMap<DbCollectionWork, CollectionWorkMessage>();

我可以这样做:

var worklists = dbContext.Worklists.Include(wl => wl.Work).ToList();
var worklistWork = autoMapper.Map<List<CollectionWorkMessage>>(worklists[0].Work);

var worklistResponse = new WorklistResponse
{
    Worklists = { new WorklistMessage
    {
        Work = { worklistWork }
    }}
};

这似乎是我可以设置Work属性的唯一方法,它是一个protobuf3 RepeatedField<CollectionWorkMessage>,它在自动生成的protobuf类中成为只读属性。

我希望能够使用自动映射器构造消息。

我正在使用AutoMapper 8.0,Grpc 1.19.0,Protobuf 3.7.0和EF Core 2.2.4

0 个答案:

没有答案