ASP.NET Web API OData可以返回非集合属性吗?

时间:2014-03-21 20:10:10

标签: json asp.net-web-api odata

我有以下课程:

    public class WeeklyReport
    {
        public IEnumerable<DailyReport> DailyReports { get; set; }

        public int? TotalReport
        {
            get
            {
                return DailyReports.Sum(x => x.ReportId);
            }
        }

        public string Title
        {
            get
            {
                return "Weekly Report";
            }
        }
    }

    public class DailyReport
    {
        public string Office { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string ReportTo { get; set; }
        public DateTime Collection { get; set; }
        public int? Leads { get; set; }
    }

在OData控制器中的一个方法中,我返回WeeklyReport的IQueryable。 但是,当查询OData端点时,返回的JSON类似于:

{
"odata.metadata": "http://localhost:546/odata/$metadata#WeeklyReports",
"value": [
    {
        "DailyReports": [
            {
                "Office": "002",
                "Name": "First Last",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            },
            {
                "Office": "002",
                "Name": "Agent, ",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            }
        ]
    },
    {
        "DailyReports": [
            {
                "Office": "002",
                "Name": "First Last",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            },
            {
                "Office": "002",
                "Name": "Agent, ",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            }
        ]
    }
]

有没有办法将ASP.NET Web API OData设置为返回WeeklyReport.TotalReport和WeeklyReport.Title?

谢谢!

1 个答案:

答案 0 :(得分:1)

我转载了这个问题。我相信你正在使用ODataConventionModelBuilder来构建Edm模型。默认情况下,构建器仅添加具有public get的属性并设置为Edm模型。添加无操作设置后,问题得以解决。你可以尝试一下。

public class WeeklyReport
{
    public IEnumerable<DailyReport> DailyReports { get; set; }

    public int? TotalReport
    {
        get
        {
            return DailyReports.Sum(x => x.ReportId);
        }
        set{}
    }

    public string Title
    {
        get
        {
            return "Weekly Report";
        }
        set{}
    }
}