slashCoder
slashCoder

Reputation: 1549

How to include read-only property in an OData query

I have the following models:

public class Employee
{
  public int EmployeeId { get; set; }

  public string Name { get; set; }

  [...]

  public int OfficeId { get; set; }      

  public string OfficeInfo
  {
    get { return Office.Info; }
  }

  public Office Office { get; set; }
}

public class Office
{
  public int OfficeId { get; set; }

  public string Info { get; set; }
}

I have a grid in the client side which rows I want to feed with instances of Employee, including the OfficeInfo in one of the columns, so I'm consuming it through the following query:

"/odata/Employees?$expand=Office&$select=EmployeeId,Name,OfficeInfo"

I have both entities registered in the IEdmModel:

private static IEdmModel GetEDMModel()
{
  ODataModelBuilder builder = new ODataConventionModelBuilder();

  builder.EntitySet<Employee>("Employees");
  builder.EntitySet<Office>("Offices");

  [...]
}

and my Get action looks like this:

[EnableQuery]
public IQueryable<Employees> Get()
{
   [...]
}

but I keep getting this Exception:

"Could not find a property named 'OfficeInfo' on type 'Xds.Entities.Employee'"

What am I missing here?

Upvotes: 0

Views: 1283

Answers (2)

Andriy Tolstoy
Andriy Tolstoy

Reputation: 6090

You could mark the property OfficeInfo as required or add this property explicitly:

  • Noting as required:

    builder
          .EntitySet<Employee>("Employees")
          .EntityType
          .Property(_ => _.OfficeInfo)
          .IsRequired();
    
  • Adding explicitly:

    builder
          .EntitySet<Employee>("Employees")
          .EntityType
          .Property(_ => _.OfficeInfo)
          .AddedExplicitly = true;
    

Upvotes: 1

Karata
Karata

Reputation: 1149

You can check your model metadata and see whether following appears under 'Xds.Entities.Employee' type.

<Property Name="OfficeInfo" Type="Edm.String" />

Since it is a readonly property, you should turn on isQueryCompositionMode to get it shown in the model, like (can pass real HttpConfiguration there):

ODataModelBuilder builder = new ODataConventionModelBuilder(new System.Web.Http.HttpConfiguration(), true);

After that, the query should work.

Note that flag is marked as for testing purpose, but it should be fine if you manually verify your metadata.

Upvotes: 0

Related Questions