
创建应用程序
添加引用
install-package entityframework 、 Install-Package Microsoft.AspNet.Odata 、 Install-Package Jquery
添加实体,并通过EntityFramework 生成数据
在Controller文件夹下创建两个类分别为 ProductsController、SuppliersController,并且都继承 ODataController,在WebApiConfig类中配置路由。
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务 // Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
); //构建路由服务
var route = config.MapODataServiceRoute("odata", "Odata", model: GetModel()); //第二个参数Odata是前缀
}
public static Microsoft.OData.Edm.IEdmModel GetModel()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");//第二个参数Products对应ProductsController
builder.EntitySet<Supplier>("Suppliers");
return builder.GetEdmModel();
}
路由配置后F5,如果显示如下界面说明已配置成功。
构建查询服务
[EnableQuery]
public IQueryable<Product> Get()
{
return _dbContext.Products;
} [EnableQuery]
public SingleResult<Product> Get([FromODataUri] int key)
{
IQueryable<Product> result = _dbContext.Products.Where(p => p.Id == key);
return SingleResult.Create(result);
}
获取所有产品信息
获取产品为1的对象
获取产品为1的供应商