可以有多个OData路由,而无需使用
[EnableQuery]
属性,但它有点复杂。
首先,您需要注册您的路线:
internal static IServiceCollection AddCustomizedODataRoute(this IServiceCollection services, string routeName, Func<IEdmModel> GetEdmModel)
{
services
.AddMvc()
.AddOData(opts =>
{
opts.AddRouteComponents(routeName, GetEdmModel(), builder =>
{
// customize builder, e.g. custom URI resolver
// builder.AddSingleton<ODataUriResolver, CustomODataUriResolver>();
});
// odata operations allowed on the route
opts.Filter();
opts.OrderBy();
});
return services;
}
哪里
GetEdmModel
构建您的模型。它可以根据您的需要进行细化,并且仅针对特定的路线创建;其他路线将有自己的模型。
services.AddCustomizedODataRoute("route1", () =>
{
// OData ignores all NotMapped property, so we need to add them manually
var builder = new ODataConventionModelBuilder();
builder.EntitySet<MyEntity>(nameof(MyEntity));
return builder.GetEdmModel();
});
然后,您需要一种基于HTTP查询应用OData查询的方法:
public static IQueryable<T> ApplyODataQuery<T>(this IQueryable<T> source, string oDataRouteName, HttpContext httpContext)
{
if (httpContext == null)
return source;
// oDataRouteName should match the name used during registration
httpContext.ODataFeature().RoutePrefix = oDataRouteName;
var container = httpContext.Request.CreateRouteServices(oDataRouteName);
var model = (IEdmModel)container.GetService(typeof(IEdmModel));
var queryContext = new ODataQueryContext(model, typeof(T), null);
var queryOptions = new ODataQueryOptions(queryContext, httpContext.Request);
return queryOptions
.ApplyTo(source, new ODataQuerySettings
{
HandleNullPropagation = HandleNullPropagationOption.True
})
.Cast<T>();
}
最后,在控制器中:
[HttpGet]
public MyResponseType Get()
{
// note that this gives you more flexibility on the return type
var models = _Dbcontext.MyEntitys.ApplyODataQuery("route1", HttpContext);
// do whatever
return new MyResponseType();
}