Madeline Schimenti
Madeline Schimenti

Reputation: 1

Cannot implicitly convert type.. Error

I've googled this error and got a variety of results, none really working for my situation.

I currently have a CRUD (scaffold) for the Identity in Web Forms that will work as a user profile.

I have this

public IQueryable<WebApplication2.Models.MyAppUser> GetData()
{
    var currentUser = _db.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);
    return currentUser;
}

However I get this error:

Error 1 Cannot implicitly convert type 'WebApplication2.Models.MyAppUser' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

As I said I did some research. I believe it's because I am trying to return a var.. however I don't know how to properly handle this. I've tried creating a function that does it but that didn't work out for me either.

Please help.

I am using Web forms (not MVC)

Upvotes: 0

Views: 1612

Answers (2)

Peyman
Peyman

Reputation: 3138

First: why return IQueryable<> you need only return one object

Second: cuurentUser in Entity obejct you should cast it to your domain model:

public WebApplication2.Models.MyAppUser GetData()
{
    var currentUser = _db.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);
    return currentUser ;
}

Or

public IQueryable<WebApplication2.Models.MyAppUser> GetData()
{
   return _db.Users.Where(u => u.UserName == User.Identity.Name);                       
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

You are either using a wrong LINQ method, or a wrong method signature.

The FirstOrDefault method returns a single MyAppUser, not an IQueryable<MyAppUser>. You have two choices for fixing this:

  • Replace FirstOrDefault call with Take(1) call

Here is how:

return _db.Users.Where(u => u.UserName == User.Identity.Name).Take(1);
  • Change the method signature to return MyAppUser instead of IQueryable<MyAppUser>

Both fixes will get your code to compile. Picking one over the other depends on the use of the GetData method in your application.

Upvotes: 1

Related Questions