OData 包括 "Custom Properties" 通过部分 类 添加到 Entity Framework 模型

OData include "Custom Properties" added to Entity Framework models via Partial Classes

我创建了一个部分 class 文件来向我的 Entity-Framework 生成的模型添加新属性。

我正在使用 WebAPI + OData,$metadata 没有列出我的 new/custom 属性,所以 JSON 它 returns 不包括我的 new/custom 属性。

例如,假设我的实体是 "Person"

"Person" 有一个数据库 属性;夫妻人数;一个在 $metadata 中返回的 int,如下所示: <Property Name="NumSpouses" Type="Edm.Int32"/>

太好了,但是我在单独的文件中添加了这样的 属性,with a partial class:

public partial class Person {
  ...
  public string MarriedStatus { 
     get { return this.NumSpouses==0 ? "Single" : "Married"; }
  }
  ... 
}

如何在我的 OData 响应中获得此 属性?

<Property Name="MarriedStatus" Type="Edm.String"/>

目前,如果我在 $expand 中请求 MarriedStatus(就好像它是一个导航属性...它不是 [我想我会尝试 $expand无论如何,就好像它神奇地提供了自定义属性]),我会收到这样的消息:

{
  "odata.error":{
    "code":"","message":{
      "lang":"en-US","value":"The query specified in the URI is not valid. Could not find a property named 'MarriedStatus' on type 'fakeDataModels.Person'."
},"innererror":{
  "message":"Could not find a property named 'MarriedStatus' on type 'fakeDataModels.Person'.","type":"Microsoft.Data.OData.ODataException","stacktrace":"   at ..."
    }
  }
}

MarriedStatus 是一个 calculated/readonly 属性。 OData 的 ASP.NET 实现当前不支持此类属性。作为解决方法,添加一个 setter 抛出 NotImplementedException.

    public string MarriedStatus {
        get { return this.NumSpouses > 0 ? "Married" : "Single"; }
        set { throw new NotImplementedException(); }
    }

可选,如果您使用的是 OData V4,您可以注释 MarriedStatus 以指定它是计算的。参见 Yi Ding's answer to OData read-only property。但注释仅供参考;它不会阻止客户端尝试设置计算的 属性(例如,在 POST 请求中)。

除了lencharest的回答。您应该使用 Entity Framework fluent API 的 Ignore() 函数而不是 [NotMapped] 属性。因为 OData 查找此属性以忽略序列化的属性。如果你用fluentAPI就不会出现这个问题

dbModelBuilder.Entity<TEntity>()
    .Ignore(i => i.ComputedProperty);