Home > Software engineering >  C# couldn't get class property value from lambda expression
C# couldn't get class property value from lambda expression

Time:12-15

I'm making a CRUD Service for my web API with ASP.NET Core 5 and Entity Framework Core. I'm trying to make a method, that gets one user from database by some of its values, which are chosen using lambda expression. The problem is that I can't get value of the property of the class with which I'm comparing the value of the user model.

The method code is:

public async Task<UserModel> FindOne(Expression<Func<UserModel, bool>> predicate)
{
    var candidates = await _context.Users.Where(predicate).ToListAsync();
    var user = candidates.First();
    return user;
}

Here is how I call the FindOne method:

[HttpPost("register")]
public async Task<ActionResult<UserLoginResponseModel>> RegisterUser(UserRegisterRequestModel requestModel)
{
    var model = new UserModel(requestModel);
    var email = model.Email;

    var candidate = await _service.FindOne(u => u.Email == email);
            
    if (candidate is not null)
    {
        return BadRequest($"User with email {model.Email} is already registered");
    }

    // continuation of the code

}   

I debugged my program and the value of model.Email in the predicate lambda expression is:

value(.Constant<API.Controllers.UserController <>c__DisplayClass4_0>(API.Controllers.UserController <>c__DisplayClass4_0).model).Email

But if I hard-code the value of model.Email, everything will work.

Entity Framework Core version: 5.0.12

I don't know how to fix it. It would be really good if someone can help me.

CodePudding user response:

The answer is that I had to use FirstOrDefaultAsync() instead of FirstAsync():

public async Task<UserModel> FindOne(Expression<Func<UserModel, bool>> predicate)
{

    var user = await _context.Users.Where(predicate).FirstOrDefaultAsync();
    return user;

}

Thanks to everyone who tried to help me.

  • Related