OData包括"自定义属性"通过Partial Classes添加到Entity Framework模型

时间:2016-03-31 22:33:24

标签: entity-framework odata

我制作了一个部分类文件,为我的Entity-Framework生成的模型添加新属性。

我正在使用WebAPI + OData,$元数据没有列出我的新/自定义属性,因此它返回的JSON不包含我的新/自定义属性

例如,让我们说我的实体是"人"

&#34;人&#34;有一个数据库属性; NumSpouses;一个在$元数据中返回的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"/>

目前,如果我在MarriedStatus中询问$expand(好像它是一个NavigationProperty ......它不是[我以为我试试$扩展无论如何好像它神奇地提供了自定义属性]),我得到这样的消息:

{
  "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 ..."
    }
  }
}

2 个答案:

答案 0 :(得分:5)

MarriedStatus是计算/只读属性。 OData的ASP.NET实现目前不支持此类属性。要解决此问题,请添加一个抛出NotImplementedException

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

或者,如果您使用的是OData V4,则可以注释MarriedStatus以指定计算它。见Yi Ding's answerOData read-only property。但注释只是建议性的;它不会阻止客户端尝试设置计算属性(例如,在POST请求中)。

答案 1 :(得分:2)

除了lencharest的答案。您应该使用Entity Framework Fluent API的Ignore()函数而不是[NotMapped]属性。因为OData查找此属性以忽略序列化的属性。如果您使用流畅的API,则不会出现此问题。

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