I finally find out what was the problem. In fact, the context was not properly initialized (due to a wrong DatabazeInitializer, but there were data in the DB), the code shown above is perfectly working now.
Expression<Func<T, bool>>, having trouble with the Repository pattern and Entity Framework [closed]
-
19-06-2023 - |
Question
I've recently jumped in the Repository pattern while using Entity Framework. I wrote a basic CRUD interface that I implemented for each entity that I had. I also wanted to go further by using Expression> but there's a little problem. Enougth talk, let's show code.
Here's my User entity :
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
And here's the method that annoy me a lot :
public async Task<User> FindOne(Expression<Func<User, bool>> wheres)
{
using (MyContext context = new MyContext())
{
User user = await context.Users.SingleOrDefaultAsync(wheres);
return user;
}
}
And here's how I call it :
// user.Username is set by the user via a form
User findOne = await _usersRepository.FindOne(u => u.Username == user.Username);
The problem is that I have a null value in my variable and I'm sure that I have one record that matches my condition !
Here is a copy/paste of the "wheres" value when I step into the FindOne function :
{u => (u.Username == value(MyApi.Controllers.UsersController+<>c__DisplayClass1e).username)}
In fact, I dunno how to debug that...
Any help would be greatly appreciated. Thanks.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow