ASP.NET WebAPI。返回已关联的实体

时间:2015-08-18 12:16:04

标签: c# asp.net-web-api odata

我是asp.net和web的初学者。

我需要为http-request添加参数以提取链接的实体,这些实体将作为响应中的JSON-object返回。默认情况下,此参数必须设置为false,并且JSON对象必须与数据库中的实体(表)相同。当参数设置为true时,JSON-object必须包含所有链接的实体。

例如,我有2个模型StreetType和Street:

public abstract class BaseDictionary
{   
   public int ID { get; set; } 
   public string Name { get; set; }
}

public class Street : BaseDictionary
{       
  public int StreetTypeID { get; set; }

  // create foreign key using Lazy Load (virtual)    
  public virtual StreetType StreetType { get; set; }
}

public class StreetType : BaseDictionary
{
  [IgnoreDataMember]
  public virtual ICollection<Street> Streets { get; set; }
}

予。请求:http://localhost:3761/api/Street返回JSON,如:

{
  StreetTypeID: 1,
  StreetType: null,
  Name: "Street1",
  ID: 1
}

II。请求:http://localhost:3761/api/Street?$expand=StreetType返回:

{
  StreetType: {
    Name: "StreetType1",
    ID: 1
  },
  StreetTypeID: 1,
  Name: "Street1",
  ID: 1
}

我想请求http://localhost:3761/api/Street/all并返回第二个json。
可能的解决方案是在http://localhost:3761/api/Street/all重定向到http://localhost:3761/api/Street?$expand=StreetType之后,但$expand的参数必须自动设置

我如何实现这个?

P.S。对于抽样实体Address有一些链接的实体(城市,国家/地区,街道),我不想请求http://localhost:3761/api/Address?$expand=City,Country,Street,我想简单请求http://localhost:3761/api/Address/all

在这种情况下,如何将参数all添加到请求中: http://localhost:3761/api/Address/1/allhttp://localhost:3761/api/Address/all

由于

0 个答案:

没有答案