我首先使用带有EF4.1代码的MVC3 ajaxgrid脚手架,我发现了这个错误:
无法将类型'System.Linq.IQueryable'隐式转换为'System.Data.Objects.ObjectQuery'
错误输入的代码是自动生成的:
public ActionResult GridData(int start = 0, int itemsPerPage = 20, string orderBy = "UserID", bool desc = false)
{
Response.AppendHeader("X-Total-Row-Count", repository.Users.Count().ToString());
ObjectQuery<User> users = (repository as IObjectContextAdapter).ObjectContext.CreateObjectSet<User>();
users = repository.Users.Include(u => u.Role); //ERROR HERE
users = users.OrderBy("it." + orderBy + (desc ? " desc" : ""));
return PartialView(users.Skip(start).Take(itemsPerPage));
}
这是用户存储库方法和角色外键
public IQueryable<Entities.User> Users
{
get { return context.Users; }
}
public IQueryable<Entities.Role>Roles
{
get { return context.Roles; }
}
我如何解决转换?
答案 0 :(得分:1)
摆脱Lambda并使用相关对象:
var users = repository.Users.Include("Role"); //ERROR HERE
假设实体User具有导航属性Role。
答案 1 :(得分:0)
原因很清楚:
您拥有users
类型ObjectQuery<User>
变量,然后指定查询的变量结果IQueryable<User>
。
<强>更新强> 请尝试以下代码:
public ActionResult GridData(int start = 0, int itemsPerPage = 20, string orderBy = "UserID", bool desc = false)
{
Response.AppendHeader("X-Total-Row-Count", repository.Users.Count().ToString());
//ObjectQuery<User> users = (repository as IObjectContextAdapter).ObjectContext.CreateObjectSet<User>();
var users = repository.Users.Include(u => u.Role); //ERROR HERE
users = users.OrderBy("it." + orderBy + (desc ? " desc" : ""));
return PartialView(users.Skip(start).Take(itemsPerPage));
}