简体   繁体   中英

asp.net odata web api $select failing for related entities

My entities

public class A
{
    public int id {get;set;}
    public string Name {get;set;}
    public List<B> b {get;set;}
}
public class B
{
    public string C {get;set;}
    public string D {get;set;}
}

My controller class
[RoutePrefix("odata/A/{id}")]
[ODataRouting]
public class AsController : ApiController
{
    [Queryable]
    public async Task<HttpResponseMessage> GetA(int id)
    {
        // here i call another method that gives me List<A> result
        HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, result);
        return httpResponseMessage;

    }
}

WebApiConfig.cs
 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new ValidationActionFilter());

        // Web API configuration and services
        config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling =
        TypeNameHandling.Objects;

        var contractResolver = (config.Formatters.JsonFormatter.SerializerSettings.ContractResolver as DefaultContractResolver);
        contractResolver.IgnoreSerializableAttribute = true;

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );



        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<A>("As");
        builder.EntitySet<B>("b");

        config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
        }
    }

When I run query /odata/A/1?$select=Name , I get json with only one field, Name. But when I run query /odata/A/1?$select=b, I get output with exception

{ 
    "$type":"System.Web.Http.HttpError, System.Web.Http",
    "Message":"The query specified in the URI is not valid.",
    "ExceptionMessage":"Could not find a property named 'b' on type 'A'.",
    "ExceptionType":"Microsoft.Data.OData.ODataException",
    "StackTrace":"   at Microsoft.Data.OData.Query.SyntacticAst.SelectPathSegmentTokenBinder.ConvertNonTypeTokenToSegment(PathSegmentToken tokenIn, IEdmModel model, IEdmEntityType entityType)
       at Microsoft.Data.OData.Query.SyntacticAst.SelectPropertyVisitor.ProcessTokenAsPath(NonSystemToken tokenIn)
       at Microsoft.Data.OData.Query.SyntacticAst.SelectPropertyVisitor.Visit(NonSystemToken tokenIn)
       at Microsoft.Data.OData.Query.SyntacticAst.NonSystemToken.Accept(IPathSegmentTokenVisitor visitor)
       at Microsoft.Data.OData.Query.SyntacticAst.SelectBinder.Bind(SelectToken tokenIn)
       at Microsoft.Data.OData.Query.SelectExpandSemanticBinder.Parse(IEdmEntityType elementType, IEdmEntitySet entitySet, ExpandToken expandToken, SelectToken selectToken, ODataUriParserConfiguration configuration)
       at Microsoft.Data.OData.Query.ODataUriParser.ParseSelectAndExpandImplementation(String select, String expand, IEdmEntityType elementType, IEdmEntitySet entitySet)
       at Microsoft.Data.OData.Query.ODataUriParser.ParseSelectAndExpand(String select, String expand, IEdmEntityType elementType, IEdmEntitySet entitySet)
       at System.Web.Http.OData.Query.SelectExpandQueryOption.get_SelectExpandClause()
       at System.Web.Http.OData.Query.Validators.SelectExpandQueryValidator.Validate(SelectExpandQueryOption selectExpandQueryOption, ODataValidationSettings validationSettings)
       at System.Web.Http.OData.Query.SelectExpandQueryOption.Validate(ODataValidationSettings validationSettings)
       at System.Web.Http.OData.Query.Validators.ODataQueryValidator.Validate(ODataQueryOptions options, ODataValidationSettings validationSettings)
       at System.Web.Http.OData.Query.ODataQueryOptions.Validate(ODataValidationSettings validationSettings)
       at System.Web.Http.QueryableAttribute.ValidateQuery(HttpRequestMessage request, ODataQueryOptions queryOptions)
       at System.Web.Http.QueryableAttribute.ExecuteQuery(Object response, HttpRequestMessage request, HttpActionDescriptor actionDescriptor)
       at System.Web.Http.QueryableAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext)"
}

Please suggest any solution for this problem.

Thanks

Found the problem. In my actual code, C and D are fields, and not properties.

Changing them to properties solved the problem.

hj,

Try the following...

/odata/A(1)?$select=b&$expand=b

Hope this helps,

Ed Mendez

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM