一个控制器中有多个IQueryable?

时间:2012-05-16 18:25:45

标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api

我的整个数据库都有一个控制器,代码如下:

public class YogaController : DbDataController<Yoga.Models.YOGAEntities>
{
    public YogaController()
    {
    }

    public IQueryable<Yoga.Models.Action> GetActions(int BugId)
//GetActions retrieves "actions" table from the db, not Actions in MVC term 
    {
        return DbContext.Actions.Where(x => x.FK_BugsID == BugId);
    }
    public IQueryable<Yoga.Models.Label> GetRequiredLabels()
    {
        return DbContext.Labels.Where(x => x.IsRequired == true);
    }
    public IQueryable<Yoga.Models.Role> GetRoles()
    {
        return DbContext.Roles;
    }
    public IQueryable<Role> GetRoles2() //TODO: finish this
    {
        return DbContext.Roles.Where(x => x.RoleID == 1);
    }
    public IQueryable<Tag> GetTags(int actionid)
    {
        return DbContext.Tags.Where(x => x.J_Tags.Any(y => y.FK_ActionID == actionid));
    }
}

如您所见,我在一个控制器中有多个IQueryable,每个查询一个不同的表。这是被禁止的吗?因为当我转到localhost/api/Yoga/GetActionslocalhost/api/Yoga/GetRequiredLabels时,我收到错误消息:

Multiple actions were found that match the request: 
 System.Linq.IQueryable`1[Yoga.Models.Label] GetRequiredLabels() on type Yoga.Controllers.YogaController
 System.Linq.IQueryable`1[Yoga.Models.Role] GetRoles() on type Yoga.Controllers.YogaController
 System.Linq.IQueryable`1[Yoga.Models.Role] GetRoles2() on type Yoga.Controllers.YogaController

当我禁用除IQIeryable之外的所有内容时,结果很好。

我搜索了类似的问题并检查了我的路由设置,控制器路径和名称没有冲突。

我的路线(默认生成):

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        //routes.MapRoute(
        //    name: "Default",
        //    url: "{controller}/{action}/{id}",
        //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

MVC4可能会将您的HTTP谓词(Get)与名称以“Get”开头但没有参数的所有方法相匹配。尝试强制操作名称:

[ActionName("GetRequiredLabels")]
public IQueryable<Yoga.Models.Label> GetRequiredLabels()
...
[ActionName("GetActions")]
public IQueryable<Yoga.Models.Action> GetActions(int BugId)
... // etc

修改

根据您粘贴的路线和控制器,我认为您的路线应为:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

即。它应该有{action}。如果您只有一个“Get”方法,则默认的MVC4路由将起作用。由于您有多个,因此您必须强制它根据路线选择操作。