ASP.NET API / C#ObjectResult - 添加更多"列"在运行时

时间:2016-04-20 17:01:56

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

下面是一个Web服务方法的简化版本,它从SQL存储过程中提取表格数据以传递到前端。 " allLocations"方法返回的对象是ObjectResult类型。我怎么能添加更多"列"在运行时?将根据某些if / else条件插入新列的值。任何帮助表示赞赏。

    // GET: api/Locations/GetLocations
    [HttpGet]
    public IEnumerable<sp_GetLocations_Result> GetLocations()
    {

        // Initial object allLocations of ObjectResult type
        var allLocations = geoDB.sp_GetLocations(); 

        foreach (var loc in allLocations) 
        {
           // at runtime add more columns to tabular 
           // data and populate them based on some conditions
        }

        return allLocations; // allLocations object with more column now
    }

实施例: 1)初始allLocations

Country     City
France      Paris
USA         New York

2)添加更多列后返回的对象

Continent           Country     City

Europe              France      Paris

North America       USA         New York

1 个答案:

答案 0 :(得分:0)

我尝试在运行时合并两个ObjectResult类型对象以实现扩展的表格数据结构并不成功,但我找到了一个简单的解决方案,我想分享。

您基本上修改了实例化geoDB的模型类sp_GetLocations_Result - 您再添加一个Continent属性:

public partial class sp_GetLocations_Result
{
    public string Country { get; set; }
    public string City{ get; set; } 
    public string Continent {get; set;}
}

然后在foreach循环内部,根据一些if / else条件将该大陆值分配给该属性。换句话说,您从存储过程中收到两个值,city和country,并在运行时添加第三个值continent。

foreach (var loc in allLocations) 
{
       if(some condition here)
       {
         loc.continent = "Europe"; // for example
       }
}

最后,您可以为前端准备好扩展的表格结构。