Reputation: 194
I'm new to Entity Framework and would like some help with my Read Methods.
I have this User
class and its UserDAO
with my methods.
I´ve already created
public IList<User> ReadUsersByName(string _name) {
var search = from m in context.Users
where m.Name.Contains(_name)
select m;
IList<User> _users = search.ToList();
return _users;
}
to search for Users by their name.
Other than Name, my Users have other attributes that I´d like to seach for (like their Age for example).
Do I need to replicate most of this code just changing "Name" for "Age"?
I´d like to create only one method and pass the Search Value AND Search Field by param. Is it possible?
Upvotes: 0
Views: 268
Reputation: 4561
You can pass where clauses into functions:
See this answer: C# Linq where clause as a variable
So, you could write something like this:
public IList<User> ReadUsersWhere(Expression<Func<User, bool>> whereClause) {
return context.Users.Where(whereClause).ToList();
}
And you'd call it like this:
foo.ReadUsersWhere(u => u.Name.Contains("Joe"));
But at that point, you're basically just exposing an IQueriable/reinventing the wheel.
Upvotes: 1