【发布时间】:2012-05-16 18:25:44
【问题描述】:
我的整个数据库都有一个控制器,代码如下:
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/GetActions 或localhost/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
当我禁用除一个 IQueryable 之外的所有 IQueryable 时,结果很好。
我搜索过类似问题并检查了我的路由设置,控制器路径和名称没有冲突。
我的路线(默认生成):
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 }
);
}
有什么想法吗?
【问题讨论】:
-
为什么要返回 IQueryable 作为操作方法的返回类型?
-
这是我看到的使用 MVC4 的教程:goo.gl/mqzDD 前端使用 upshot.js 并直接处理 IQueryable。我不太确定确切的机制
-
返回 IQueryable 允许您在该操作的查询字符串中使用 OData 过滤器和选项
-
谢谢。没想到!
-
如果你是新手,我会说坚持传统的方式返回
ActionResult并使用包含你需要的数据的模型,这样你就不必捏造使用路线等来获得这种自定义行为:)
标签: asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api