OData在启用camelcasing时抱怨缺少id属性

时间:2016-09-01 10:36:18

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

我想启用我的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();

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我解决此问题的方法是从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();
    }

然后按照约定将DTO与Automapper一起使用:

[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";
        }
    }