如何重载Odata V2控制器方法以接受多个值作为参数?

时间:2016-10-23 03:14:38

标签: asp.net entity-framework asp.net-web-api odata

我是ASP.NET MVC Web开发的新手。我只是试图将一个简单的odata控制器方法重载几天,但一次又一次失败。我想知道这背后的奥秘。请帮帮我......

这是我的EducationInfo Model类......

public partial class EducationInfo
{
    [Key]
    public int EducationID { get; set; }

    [ForeignKey("UserID")]
    public int UserID { get; set; }

    [Required]
    public string Title { get; set; }

    [Required]
    [StringLength(50)]
    public string EducationLevel { get; set; }

    public string Department_Group { get; set; }

    public string InstituteName { get; set; }

    [Required]
    public string Board_University_Name { get; set; }

    [StringLength(30)]
    public string Duration { get; set; }

    public DateTime PassingYear { get; set; }

    [StringLength(30)]
    public string Result { get; set; }

    public virtual UserInfo UserInfo { get; set; }
}

这是我的一个EducationInfoesController GET方法,它接受EducationID作为参数

// GET: odata/EducationInfoes(5)
    [EnableQuery]
    public SingleResult<EducationInfo> GetEducationInfo([FromODataUri] int key)
    {
        return SingleResult.Create(db.EducationInfoes.Where(educationInfo => educationInfo.EducationID == key));
    }

我希望以这样的方式重载此方法,即它可能需要2个参数[例如GetEducationInfo(int UserID,string EducationLevel)]并且只返回基于两个参数(UserID和EducationLevel)组合的单个结果。

我已经尝试通过以下代码重载此方法...

// GET: odata/EducationInfoes(5, "bachelor")
    [EnableQuery]
    public SingleResult<EducationInfo> GetEducationInfo([FromODataUri] int key, string eLevel)
    {
        return SingleResult.Create(db.EducationInfoes.Where(educationInfo => educationInfo.UserID == key && educationInfo.EducationLevel == eLevel));
    }

但是,当我通过此网址http://localhost:10194/odata/EducationInfoes(5, "Bachelor")向我的WebService发送GET请求时,我收到此消息:

  

找不到与请求URI匹配的HTTP资源&#39; http://localhost:10194/odata/EducationInfoes(5,&#34; Bachelor&#34;)&#39;。

如果我将默认方法更改为以下...

// GET: odata/EducationInfoes(5)
    [EnableQuery]
    public SingleResult<EducationInfo> GetEducationInfo([FromODataUri] int key)
    {
        return SingleResult.Create(db.EducationInfoes.Where(educationInfo => educationInfo.UserId== key));
    }

并请求使用此网址http://localhost:10194/odata/EducationInfoes(3)并收到此消息

  

行动&#39; GetEducationInfo&#39;在控制器&#39; EducationInfoes&#39;返回包含多个元素的SingleResult。 SingleResult必须包含零个或一个元素。   返回此消息是因为每个用户都有多个教育信息存储在EducationInfo表中。

但我必须单独获取每个EducationInfo结果,或者根据UserID和EducationLevel获得单个结果,但不能基于EducationID。请帮帮我......

0 个答案:

没有答案