2014-03-05 33 views
6

我有一个使用OData的(System.Web.Http.OData,5.1.0.0)一个简单的WebAPI2服务。用户可以点击/odata/$metadata获取可用的实体和属性。我正在寻找一种方式来扩展这些元数据的附加信息,比如将“显示名称”值添加到属性中。将任意数据添加到WebAPI中的OData元数据中?

我发现有关这听起来像它就是我想要的“注释”,但我无法找到任何explanining如何在我的情况下使用,或者如果它甚至有可能。我试图做类似如下:

model.SetAnnotationValue(((IEdmEntityType)m.FindType("My.Thing")).FindProperty("SomeProperty"), 
     namespaceName:"MyNamespace", 
     localName: "SomeLocalName", 
     value: "THINGS"); 

类型/属性名称都是正确和调用成功,但OData的EDMX文件不包含此注解。有什么方法可以公开这些注释或以其他方式做我想要的吗?

更新
仍然在它。我一直在寻找ODataMediaTypeFormatters作为解决这个问题的可能方法。有一个ASP.NET sample project演示了如何实例添加注释实体。关闭,但不正是我想要的,所以现在我试图找到一种方法来扩展任何产生类似的方式中的元数据文件。

回答

9

我想出了一个办法做到这一点。下面的代码添加自定义空间前缀“myns名字”,然后在模型属性增加了一个注释:

const string namespaceName = "http://my.org/schema"; 
var type = "My.Domain.Person"; 
const string localName = "MyCustomAttribute"; 

// this registers a "myns" namespace on the model 
model.SetNamespacePrefixMappings(new [] { new KeyValuePair<string, string>("myns", namespaceName), }); 

// set a simple string as the value of the "MyCustomAttribute" annotation on the "RevisionDate" property 
var stringType = EdmCoreModel.Instance.GetString(true); 
var value = new EdmStringConstant(stringType, "BUTTONS!!!"); 
m.SetAnnotationValue(((IEdmEntityType) m.FindType(type)).FindProperty("RevisionDate"), 
         namespaceName, localName, value); 

请求的OData元数据文件应该给你这样的事情:

<edmx:Edmx Version="1.0"> 
    <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0"> 
     <Schema Namespace="My.Domain"> 
      <EntityType Name="Person"> 
       <Key><PropertyRef Name="PersonId"/></Key> 
       <Property Name="RevisionDate" Type="Edm.Int32" Nullable="false" myns:MyCustomAttribute="BUTTONS!!!"/> 
     </Schema> 
    </edmx:DataServices> 
</edmx:Edmx> 
+0

@raddium我有使用此实施,它完美的作品,我面临的一个问题,我想在<的EntityType名称=“人”>添加自定义属性。这可能吗?尝试通过删除.FindProperty(“RevisionDate”)。 – Shivkumar