首页 > 解决方案 > OData-query is throwing error for $expand query

问题描述

There are two tables "Task" and "Client". Both this tables are related with ClientId (foreign key).

In this query I'm trying to get the client name based on ClientId from Task table with $expand keyword. Below is the query and Entity classes.

OData Query : http://localhost:52484/Task?$expand=Client($select=Name)

 public class Task: GeneralTask
{
    public Task() { }

    public Task( 
        int clientId, 
        string title, 
       )
    { 
        this.Title = title;
        this.ClientId = clientId;
    }
}


 public abstract class GeneralTask
{
    protected GeneralTask()
    {
    }
    public string Title { get; set; }

    public int ClientId { get; set; }
    public virtual  Client Client { get; set; }

}

But I get the below error.

Error Message :"The query specified in the URI is not valid. The property 'Client' cannot be used in the $expand query option."

Any help would be appreciated.

标签: asp.net-web-apiodata

解决方案


We need to enable OData Model Bound Attributes which you can do globally with the middle line in the following block(WebApiConfig.cs file)

ODataModelBuilder builder = new ODataConventionModelBuilder();
config.Count().Filter().OrderBy().Expand().Select().MaxTop(null); //new line
builder.EntitySet<DB.Project>("Projects");

推荐阅读