Assign DbSet and query result to one variable

I use the following code so that users can search for other registered users to add them to their 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());
}

But I get an error on line 9 in regUsers = regUsers.Where(..), stating:

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

How can I reuse a variable regUsers?

+4
source share
4 answers

The error is pretty clear.

There are two different types in the code:

  • db.Users: a DbSet<User>
  • regUsers.Where(s => s.User.LastName.Contains(searchString)): a IQueryable<User>

Using this statement:

var regUsers = db.Users;

You declare regUsersas a type of the right side of an assignment: DbSet<User>.

Where() , Where() DbSet<User>.

(IQueryable<User>, ):

IQueryable<Users> users = db.Users;

Where() :

users = users.Where(s => s.User.LastName.Contains(searchString));

, :

IQueryable<User> users = db.Users;

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

return View(users.ToList());
+1

IQueryable<User> regUsers = db.Users;

db.Users DbSet, , Where, regUsers, - , .

EDIT: , AsQueryable . regUsers IQueryable.

+6

:

regUsers = regUsers.Where(s => s.User.LastName.Contains(searchString)).AsQueryable();

!

:

AsQueryable()?

EDIT:

:

IQueryable<User> users = db.Users;

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

return View(users.ToList());
+3

, , , View:

[Authorize(Roles = "RegisteredUsers")]
public ActionResult Index(string searchString)
{   
    if (!String.IsNullOrEmpty(searchString))
    {
        return View(db.Users.Where(s => s.User.LastName.Contains(searchString)).ToList);
    }

    return View(new List<User>());
    //or if you want to return all users:
    return View(db.Users.ToList()); //you might want to consider `Skip` and `Take`
}

Special thanks to @CodeCaster: If your request becomes more complex:

[Authorize(Roles = "RegisteredUsers")]
public ActionResult Index(string searchString)
{   
    IQueryable<User> query = db.Users;
    if (!String.IsNullOrEmpty(searchString))
    {
        query = query.Where(s => s.User.LastName.Contains(searchString));
    }

    //additional filtering can be applied to `query`

    return View(query.ToList());    
}
+1
source

Source: https://habr.com/ru/post/1621270/


All Articles