Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert lambda expression to delegate type

I'm trying to grab the first user from a SQL database using Entity model that is talking to a already existing database that has a userID of the user I am looking for. This and a second error appear.

Cannot convert lambda expression to delegate type System.Func<iomnientitylibrary.user,bool> because some of the return types in the block are not implicitly convertible to the delegate return type.

Cannot implicitly convert type int to bool.

public user GetUser(int userID)
{
     using (var context = new iomniEntities())
    {
        user u = context.users.FirstOrDefault(user => user.userID);

        return u;
    }
}

context.users.ToList() is working properly but I don't want to be that inefficient.

like image 598
ggcodes Avatar asked Feb 16 '23 20:02

ggcodes


2 Answers

When using the expression:user u = context.users.FirstOrDefault(user => user.userID); the return type is of userID ( this is determined by the 2nd part of Lambda expression) and NOT of type: 'user' , which the statement expects as per the declaration: user u

So, if you want to return a single user whose userID is 'userID', use:

user u = context.users.FirstOrDefault(user => user.userID==userID);

OR you can also use:

user u = context.users
         .Where(user => user.UserId==UserID)
         .Select(user => user).Single();

Also make sure you have the Using statement: using System.Linq;

like image 176
R.C Avatar answered Feb 24 '23 06:02

R.C


I think you just have your syntax off a bit. Try:

public user GetUser(int intUserID)
{
     using (var context = new iomniEntities())
    {
        user u = context.users.Where(u => u.userID == intUserID).FirstOrDefault();

        return u;
    }
}

Or to hold onto your version, it just needs touched up:

public user GetUser(int intUserID)
{
     using (var context = new iomniEntities())
    {
        user u = context.users.FirstOrDefault(user => user.userID == intUserID);

        return u;
    }
}
like image 20
ethorn10 Avatar answered Feb 24 '23 06:02

ethorn10