如何在 Web API 中使属性可为空
本文关键字:属性 Web API | 更新日期: 2023-09-27 17:56:12
对于如下所示的模型文件:
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。似乎可为空<>不能在这里使用。感谢这里的任何帮助。
请尝试以下操作:
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var collectionProperty = builder.EntityType<WebApiEntity>().CollectionProperty<CData>(c=>c.data);
collectionProperty.IsOptional();
五月可能对某人有用。解决方案之一是使用 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 元数据图片