当 API returns 派生实体没有自己的密钥时未获得 OData 响应

Not getting OData response when API returns a derived entity not having a key of its own

我有一个这样的控制器class

public class OwnerController : ODataController
{
  [EnableQuery(MaxAnyAllExpressionDepth = 5)]
  public async Task<OwnersResponse> Get(string fileId, string token)
  {
    var response = await this._service.ListOwnersAsync(token, fileId).ConfigureAwait(false);
    return response;
  }
}

这些是我的模型 classes

public class OwnersResponse : CollectionResponseOfT<Owner>
{
}
public class CollectionResponseOfT<T>
{
  [JsonProperty("items")]
  [Key]
  public IEnumerable<T> Items { get; set; }

  [JsonProperty("offset", NullValueHandling=NullValueHandling.Ignore)]
  public int? Offset { get; set; }
}

public class Owner
{
  [JsonProperty("index", NullValueHandling = NullValueHandling.Ignore)]
  [Key]
  public int Index { get; set; }

  [JsonProperty("personId", NullValueHandling = NullValueHandling.Ignore)]
  public string PersonId { get; set; }
}

这是我的模型构建器class

public static IEdmModel GetEdmModel()
{
  var builder = new ODataConventionModelBuilder();  
  builder.EntitySet<Owner>("Owner");
  //builder.EntitySet<OwnersResponse>("OwnersResponse"); --> cannot set this as there is no key
  return builder.GetEdmModel();
}

基本上我如何使这个 API 与 OData 一起工作? 当我调用这样的 http://localhost:5000/odata/Owner 时,我得到的是正常响应,而不是像下面这样的带有 odata 上下文的响应。

{
    "@odata.context":.....
}

如果 API 直接 returns

,OData 就可以工作
public async Task<Owner> Get(string fileId, string token)
{
  var response = await this._service.GetOwnersAsync(token, fileId).ConfigureAwait(false);
  return response;
}

通过将以下内容添加到 ModeBuilder.getEdmModel() 它对我有用。

builder.EntitySet<CollectionResponseOfT<Owner>>("Owner").EntityType.HasKey(t => new {t.Offset});

我可以查询 http://localhost:5000/odata/Owner?$expand=Items($filter=contains(PersonId, 'e'))

并得到如下响应

{
"@odata.context": ...
}