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

本文关键字:运行时 API NET C#ObjectResult- 添加 ASP | 更新日期: 2024-10-19 15:19:16

下面是一个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) 初始所有位置

Country     City
France      Paris
USA         New York

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

Continent           Country     City
Europe              France      Paris
North America       USA         New York

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

我试图在运行时合并两个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
       }
}

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