0

I'm using MVC3 ajaxgrid scaffolding with EF4.1 code first and i've this error:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Data.Objects.ObjectQuery'

The code with the error in, is autogenerated:

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));
        }

This is the Users repository method and the Roles Foreign Key

  public IQueryable<Entities.User> Users
        {
            get { return context.Users; }
        }


  public IQueryable<Entities.Role>Roles
        {
            get { return context.Roles; }
        }

How can i resolve the conversion?

Francesco Cristallo
  • 2,856
  • 5
  • 28
  • 57

2 Answers2

1

Get rid of the Lambda and use the related object:

var users = repository.Users.Include("Role");  //ERROR HERE

Assuming the entity User has a navigational property Role.

Taryn
  • 242,637
  • 56
  • 362
  • 405
0

The reason is clear:

You have users variable with ObjectQuery<User> type then you assign that variable result of a query which is IQueryable<User>.

UPDATE: Try the code below:

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));
}
Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70
  • This statement is automatically made by the scaffolding, i do not know why it use a ObjectQuery Is there a way to cast or modify the users variable to made it work? if i cannot cast, how can i modify the code? Thanks – Francesco Cristallo Jan 14 '12 at 18:55
  • Thanks for the answer, unfortunately i've this error on the last but one line The type arguments for method 'System.Linq.Queryable.OrderBy(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly – Francesco Cristallo Jan 15 '12 at 01:16
  • So comment that line also, cause the string can not passed as Expression to OrderBy, and I thought there may be an Extension Method that accept string – Jahan Zinedine Jan 15 '12 at 05:35