Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign DbSet and query result to same variable

I am using the following code to allow for users to search for other registered users in order to add them to a friends list:

[Authorize(Roles = "RegisteredUsers")]
public ActionResult Index(string searchString)
{
    //list of registered users
    var regUsers = db.Users;

    if (!String.IsNullOrEmpty(searchString))
    {
        regUsers = regUsers.Where(s => s.User.LastName.Contains(searchString));
    }

    return View(regUsers.ToList());
}

Yet I am getting an error on line 9 at regUsers = regUsers.Where(..), stating:

"cannot implicitly convert type System.Linq.IQueryable<ETLToolKit.Models.User> to System.Data.entity.DbSet<ETLToolKit.Models.User>

How can I reuse the regUsers variable?

like image 388
Hannah McDade Avatar asked Dec 18 '22 21:12

Hannah McDade


1 Answers

How about

IQueryable<User> regUsers = db.Users;

db.Users is of Type DbSet, so when you do your Where call, it tries to implicitly assign a value of different type to regUsers, which doesn't work - hence the error.

EDIT: As others have pointed out, the call to AsQueryable can be omitted. regUsers is now explicitly of type IQueryable.

like image 86
Igor Ralic Avatar answered Jan 04 '23 23:01

Igor Ralic