Home > Enterprise >  Cannot implicitly convert type 'System.Linq.IQueryable<string>' to 'string'
Cannot implicitly convert type 'System.Linq.IQueryable<string>' to 'string'

Time:01-06

Code line causing the error:

Current_UserInfo.Current_First_Name = GetUser_Query.Select(m => m.First_Name).ToQueryString(); 

This is the error:

Error CS0029
Cannot implicitly convert type 'System.Linq.IQueryable' to 'string'

I am getting user name (environment) and pulling there info from database (IQueryable). Than I am storing it into a model (Current_UserInfo) so that I can use it later.

    [BindProperty(SupportsGet = true)]
    public Current_UserInfo_Model Current_UserInfo { get; set; } = default!;

    public async Task<IActionResult> OnGetAsync()
    {
        // get user name 
        String user = System.Environment.UserName.ToString();

        // search useranme from database and pull there info
        IQueryable<Staff_Model> GetUser_Query = (from m in _context1.Staff_DbSet
                                                      where m.UserName.ToUpper().Contains(user.ToUpper())
                                                      select m);

        // save there info into another model so there isn't need connect to database again 
        Current_UserInfo.Current_UserName = user;
        Current_UserInfo.Current_First_Name = GetUser_Query.Select(m => m.First_Name);
        Current_UserInfo.Current_Last_Name = GetUser_Query.Select(m => m.Last_Name);

        return Page();
    }

I also tried the following function but it tries to convert object into string and can't get the value of m.First_Name:

 Current_UserInfo.Current_First_Name = GetUser_Query.Select(m => m.First_Name).ToQueryString();
 Current_UserInfo.Current_Last_Name = GetUser_Query.Select(m => m.Last_Name).ToString();

CodePudding user response:

I think you may just need to select the FirstOrDefault from the database, check it for null, and then use the data if it's not:

public async Task<IActionResult> OnGetAsync()
{
    // get user name 
    String userName = Environment.UserName;

    // search username from database and pull their info
    Staff_Model user = _context1.Staff_DbSet.FirstOrDefault(m =>
        m.UserName.ToUpper() == userName.ToUpper());

    // save info into another model so there isn't need connect to database again 
    Current_UserInfo.Current_UserName = userName;
    Current_UserInfo.Current_First_Name = user?.First_Name;
    Current_UserInfo.Current_Last_Name = user?.Last_Name;

    return Page();
}
  • Related