简述
OData,即Open Data Protocol,是由微软在2007年推出的一款开放协议,旨在通过简单、标准的方式创建和使用查询式及交互式RESTful API。
类库
在.NET Core中想要使用OData功能的话需要添加Microsoft.AspNetCore.OData包。
dotnet add package Microsoft.AspNetCore.OData
准备模型类
public class Address
{
public string City { get; set; }
public string Street { get; set; }
}
public enum Category
{
Book,
Magazine,
EBook
}
public class Press
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Category Category { get; set; }
}
public class Book
{
public int Id { get; set; }
public string ISBN { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
public Address Address { get; set; }
public Press Press { get; set; }
}
创建Edm模型
OData使用EDM,即Entity Data Model来描述数据的结构。在Startup文件中添加创建方法。
private static IEdmModel GetEdmModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Book>("Books");
builder.EntitySet<Press>("Presses");
return builder.GetEdmModel();
}
注册OData服务
在Startup文件的ConfigureServices方法里注册OData服务。
services.AddOData();
services.AddMvc(options =>
{
options.EnableEndpointRouting = false;
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
这里要注意的是在.NET Core 2.2里,默认已经有终结点,所以要使用OData的终结点的话需要将默认选项禁用掉。
注册OData终结点
同样在Startup文件里,在其Configure方法内将原来的注册路由内容改为注册OData的终结点。
app.UseMvc(b =>
{
b.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
显示元数据
运行程序后访问https://localhost:5001/odata/$metadata地址,可以看到所有可用模型的元数据。
<edmx:Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
<edmx:DataServices>
<Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="Default">
<EntityType Name="Book">
<Key>
<PropertyRef Name="Id"/>
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false"/>
<Property Name="ISBN" Type="Edm.String"/>
<Property Name="Title" Type="Edm.String"/>
<Property Name="Author" Type="Edm.String"/>
<Property Name="Price" Type="Edm.Decimal" Nullable="false"/>
<Property Name="Address" Type="Default.Address"/>
<NavigationProperty Name="Press" Type="Default.Press"/>
</EntityType>
<EntityType Name="Press">
<Key>
<PropertyRef Name="Id"/>
</Key>
<Property Name="Id" Type="Edm.Int32" Nullable="false"/>
<Property Name="Name" Type="Edm.String"/>
<Property Name="Email" Type="Edm.String"/>
<Property Name="Category" Type="Default.Category" Nullable="false"/>
</EntityType>
<ComplexType Name="Address">
<Property Name="City" Type="Edm.String"/>
<Property Name="Street" Type="Edm.String"/>
</ComplexType>
<EnumType Name="Category">
<Member Name="Book" Value="0"/>
<Member Name="Magazine" Value="1"/>
<Member Name="EBook" Value="2"/>
</EnumType>
<EntityContainer Name="Container">
<EntitySet Name="Books" EntityType="Default.Book">
<NavigationPropertyBinding Path="Press" Target="Presses"/>
</EntitySet>
<EntitySet Name="Presses" EntityType="Default.Press"/>
</EntityContainer>
</Schema>
</edmx:DataServices>
</edmx:Edmx>








