【问题标题】:OData complains about missing id property when enabling camelcasingOData 在启用驼峰式时抱怨缺少 id 属性
【发布时间】:2017-01-09 04:53:59
【问题描述】:

我想为我的 odata 结果启用驼峰式大小写。所以我添加了EnableLowerCamelCase。但是在我启用后,我在调用时收到以下错误消息:

http://localhost/odata/Users

“[Core.DomainModel.User Nullable=True]”类型的 EDM 实例是 缺少属性“id”。

在我 EnableLowerCamelCase 之前一切正常,如果我删除它,它会再次工作。错误消息也相当混乱。它说用户缺少“id”属性。这不可能是真的。因为我将“Id”定义为键。

var builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();

var users = builder.EntitySet<User>(nameof(UsersController).Replace("Controller", string.Empty));
users.EntityType.HasKey(x => x.Id); // <--- id property

builder.GetEdmModel();

我做错了什么?

【问题讨论】:

  • 它似乎在代码中的某处寻找属性“id”,而它实际上被定义为“id”。这可能吗?
  • POCO 类用户的 Id 使用 Pascal Casing 定义,因为它应该在 C# 中。但是 EnableLowerCamelCase 的重点是将这些 PascalCased 属性转换为 camelCased 以便正确格式化 json 结果
  • 我无法复制这个,请提供更多信息,如模型
  • 我也有同样的问题 - Microsoft.AspNet.OData 6.1.0,版本控制 2.2.0,OData.Core 7.5.0

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


【解决方案1】:

我解决这个问题的方法是从 EDM 模型中删除实体键声明并在模型本身中指定它 所以我的 edm 看起来像 `

var builder = new ODataConventionModelBuilder(serviceProvider);
builder.EnableLowerCamelCase();
var subscriptionSet = builder.EntitySet<SubscriptionDTO>("Subscriptions");
  subscriptionSet.EntityType
            .Filter() // Allow for the $filter Command
            .Count() // Allow for the $count Command
            .Expand() // Allow for the $expand Command
            .OrderBy() // Allow for the $orderby Command
            .Page() // Allow for the $top and $skip Commands
            .Select(); // Allow for the $select Command

  // subscriptionSet.EntityType.HasKey(s => s.Id);
  //subscriptionSet.EntityType.EntityType.Property(s => s.Id).IsOptional();`

在模型中使用 DataAnnotations 来识别键:

public class BaseModel
  {
    [Key]
    public Guid? Id {get; set;}
    public Guid? TenantId {get; set;}
    public string Type {get; set;}
    public bool Active {get; set;} = true;

    public BaseModel() {
        this.Id = System.Guid.NewGuid();
    }

然后按照约定使用带有 Automapper 的 DTO:

[JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]

    public class BaseDTO
    {
        public Guid? Id {get; set;}
        public Guid? TenantId {get; set;}
        public string Type {get; set;}
        public bool Active {get; set;} = true;

        public BaseDTO() {
            this.Id = System.Guid.NewGuid();
        }

    }

 [JsonObject(NamingStrategyType = typeof(CamelCaseNamingStrategy))]
    public class SubscriptionDTO: BaseDTO
    {
        [JsonProperty("email")]
        public string Email {get; set;}

        public SubscriptionDTO(): base() {
           this.Type = "subscription";
        }
    }

【讨论】:

    猜你喜欢
    • 2015-10-31
    • 2018-06-25
    • 1970-01-01
    • 2013-03-04
    • 2018-03-16
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    相关资源
    最近更新 更多