繁体   English   中英

如何使用 OData EDM 配置强类型实体 ID(值对象)

[英]How to configure strongly-typed entity Ids (value objects) with OData EDM

我是 OData 和 EDM 的新手。 I'm trying to implement them in a solution in Visual Studio 2019 having a Blazor WebAssembly project and a .NET Core 3.1 web API. 我遇到的问题是在 web API 项目中。

要使用 EDM 配置 OData,我正在调用:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
//etc.
app.UseEndpoints(endpoints =>
            {
//etc.
                endpoints.Select().Filter().OrderBy().Count().MaxTop(1000);
                endpoints.MapODataRoute("api", "api", GetEdmModel());
// etc.
            });
        }
}

GetEdmModel() function 是:

private IEdmModel GetEdmModel()
        {
            var odataBuilder = new ODataConventionModelBuilder();
            odataBuilder.EntitySet<ViewStudentDto>("Students");

            return odataBuilder.GetEdmModel();
        }

在运行时我收到错误:

System.InvalidOperationException:实体集 Student 是基于类型 > MySchool.Dtos.Students.ViewStudentDto 没有定义的键

我理解错误。 它抱怨我的 DTO class ViewStudentDto 没有定义唯一标识符属性。 但它有。 它是公共的,并且该属性根据约定命名为Id 问题是该属性的类型不是 OData 规范中的 Edm 原始类型之一:

  • Edm.Boolean
  • 字节码
  • 编辑日期
  • Edm.DateTimeOffset
  • Edm.Decimal
  • Edm.持续时间
  • Edm.Guid
  • Edm.Int16
  • Edm.Int32
  • Edm.Int64
  • Edm.SByte
  • 编辑字符串
  • Edm.TimeOfDay

我的 Id 属性是一个名为StudentId的强类型 Id(一个值对象),其基础类型是System.Guid ,它映射到Edm.Guid

通过使用 TypeConverters、JsonConverters 和 EF 配置,可以将强类型 ID 与 Entity Framework Core 和 Json 序列化一起使用。 肯定可以通过某种类型转换将强类型 ID 与 EDM/OData 一起使用吗?

谁能指导我如何配置 EDM/OData 以识别我的StudentId值 object 可以解压缩为一个简单的Edm.Guid以便它不会引发此异常?

如果以上内容不足以看到我遇到的问题,这里有一个最小的复制:

https://github.com/BenjaminCharlton/ODataWithStronglyTypedIdsRepro

谢谢你的建议!

本杰明

使用构建器指定密钥:

private IEdmModel GetEdmModel()
{
    var odataBuilder = new ODataConventionModelBuilder();
    var entitySet = odataBuilder.EntitySet<ViewStudentDto>("Students");

    entitySet.EntityType.HasKey(e => e.Id);
    entitySet.EntityType.Ignore(e => e.StudentId);

    return odataBuilder.GetEdmModel();
}

并添加更新 DTO 以使用 Id 属性:

public class ViewStudentDto
{
    public Guid Id { get => StudentId.Value; set => StudentId = new StudentId(value); }

    [JsonIgnore]
    public StudentId StudentId { get; set; }

    public DateTime WhenEnrolled { get; set; }

    public string Name { get; set; }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM