【问题标题】:How to make a Property nullable in web api如何在 web api 中使属性为空
【发布时间】:2018-12-25 10:05:31
【问题描述】:

对于一个看起来像这样的模型文件:

public class WebApiEntity
{
  public string id { get; set; }
  public Collection<CData> data { get; set; }
}


public class CData
{
  public string CType { get; set; }

  public string CId { get; set; }
}

当我使用服务引用生成 ODATA 客户端时,它看起来像:

<EntityType Name="WebApiEntity">
    <Key>
    <PropertyRef Name="id" />
    </Key>
    <Property Name="id" Type="Edm.String" Nullable="false" />
    <Property Name="data" Type="Collection(NamespaceValue.CData)" Nullable="false" />
</EntityType>

它的可空属性设置为 FALSE。我需要做什么才能将其设置为 TRUE。 似乎 Nullable 不能在这里使用。感谢这里的任何帮助。

【问题讨论】:

  • 用 CData[] 代替集合类型怎么样?
  • 我认为Nullable 与它是否为可空类型有关,即int?,并且由于字符串和集合不是值类型,因此不相关。
  • @Oscar 使用数组生成同上 edm 作为集合
  • 问题标题和正文不一致。标题询问如何使其不可为空,它似乎已经是。 Body 似乎在问如何使它可以为空。
  • 感谢您的指出。更正了标题。

标签: c# asp.net-web-api odata


【解决方案1】:

请试试这个:

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var collectionProperty = builder.EntityType<WebApiEntity>().CollectionProperty<CData>(c=>c.data);
collectionProperty.IsOptional();

【讨论】:

  • 但这会让它可以为空吗?从它的外观来看,它应该使它不可为空。
  • 抱歉误解了你的问题,我已经更新了答案。
  • 谢谢,但我在构建器中没有看到任何名为 EntityType 的方法。错字?
  • 不,它不是 Typo,在新版本的 ODataConventionModelBuilder 中,方法 Entity 和 AddEntity 被替换为 EntityType 和 AddEntityType。所以在你的情况下,只需使用 builder.Entity().
  • 试过了。似乎没有帮助! :( 虽然 IsOptional() 方法似乎仅适用于此。附带说明,如果我将 COllection 替换为 Collection,它会自动变为可为空。
【解决方案2】:

可能对某人有用。 一种解决方案是使用 CData 作为结构类型(但您会受到一些限制)。结构是值类型。

public class WebApiEntity
{
    public Collection<CData> data { get; set; }
    public Collection<(String CType, String CId)> data_tuple { get; set; } 
}

public struct CData
{
    public string CType { get; set; }
    public string CId { get; set; }
}

OData 元数据:

<Property Name="data" Type="Collection(Diagnostics.Data.Diagnostics.CData)"/>
<Property Name="data_tuple" Type="Collection(System.ValueTuple_2OfString_String)"/>

OData metadata pic

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    相关资源
    最近更新 更多