返回JSon时包含内部项

时间:2016-08-18 19:38:43

标签: c# json odata

我有一个从数据库中获取的Employee类。在那个Employee类中,我想根据Employee数据库中的managerCode添加一个Manager对象,它也是一个Employee。请参阅下面的课程。

managerCode未定义为键,。我不需要递归,即我不需要经理的经理等。只需一个级别,员工和他的经理。

使用.NET 4.5,c#,OData v4

我正在使用OData发送回Employee,但是在响应中没有添加Manager部分,即使它在我尝试发送的对象中也存在。

我错过了什么? WebApiConfig中的东西?

由于

员工类,前4个字段直接从数据库中获取。

Class Employee
{
    [Key]
    public int id { get; set; }
    public string employeeCode { get; set; }
    public string employeeName { get; set; }
    public string managerCode { get; set; }

    [NotMapped]
    public Employee Manager { get; set; }
}

控制器类。 GetEmployeeById(id)将通过其经理获得员工。

[HttpGet]
[EnableQuery]
[ODataRoute("employeeById(id={id})")]
public IHttpActionResult employeeById([FromODataUri]int id)
{
    var sets = dbContext.GetEmployeeById(id);
    if (!sets.Any())
        return NotFound();
    return this.CreateOKHttpActionResult(sets);
}

WebApiConfig

public static void Register(HttpConfiguration config)
{
    config.MapODataServiceRoute("ODataRoute", "odata",GetEdmModel(), 
    new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
    config.EnsureInitialized();
}

private static IEdmModel GetEdmModel()
{
    var builder = new ODataConventionModelBuilder();
    builder.Namespace = "employee_odata";
    builder.ContainerName = "employee_odataContainer";
    builder.EntitySet<Employee>("Employee");
    builder.EnableLowerCamelCase();

    var unboundGetEmployee = builder.Function("employeeById");
    unboundGetEmployee.Returns<Employee>();
    unboundGetEmployee.Parameter<int>("id");
    unboundGetEmployee.Namespace = "employee_odata.Functions";

    return builder.GetEdmModel();

}

从WebApiConfig中删除unboundGetEmployee(不需要)。

将Employee项设置为virtualee,而不使用[NotMapped]

public virtual Manager Manager { get; set; }

控制器:

[EnableQuery]
[ODataRoute("Employee({id})")]
public IHttpActionResult employeeById([FromODataUri]int id)
{
    //handle data return normally...
    //I have to detect $expand=Manager, to fetch the actual Manager object.
    //otherwise it's null (not linked with primary key)
}

随着这些费用的变化,$ expand运作良好。

1 个答案:

答案 0 :(得分:0)

您需要添加$ expand以显示导航属性,例如

localhost\odata\employee_odata.Functions.employeeById(id=1)?$expand=Manager

为了通过Id获得员工,我建议您在控制器中使用此方法:

[EnableQuery]
public IHttpActionResult Get(int id)
{
    var sets = dbContext.GetEmployeeById(id);
    if (!sets.Any())
        return NotFound();
    return this.CreateOKHttpActionResult(sets);
}

然后像localhost\odata\Employee(1)这样的请求可以路由到该方法。