I've started building extension methods for my EF classes like below because it makes building queries so easy, and the intellisense provided helps keep people from writing a new Where() clause in code every time they do to do something.
Example Extensions to an EF User Class
public static class UserIQX
{
public static IQueryable<User> WhereInSearch(this IQueryable<User> value, string search)
{
search = search.ToLower();
return value.Where(user => user.FirstName.ToLower().Contains(search) || user.LastName.ToLower().Contains(search) || user.EmailAddress.ToLower().Contains(search));
}
public static IQueryable<User> WhereInRole(this IQueryable<User> value, RoleEnum role)
{
return value.Where(user => user.RoleID == (int)role);
}
}
Examples - "Get all admins named Bob"
protected void Page_Load(object sender, EventArgs e)
{
var search = "Bob";
//With Extensions
var activeAdmins = db.Users
.WhereInRole(RoleEnum.Admin)
.WhereInSearch(search)
.Select(u => new { EmailAddress = u.EmailAddress })
.ToList();
//Without extensions
search = search.ToLower();
var pq = db.Users
.Where(u => (
u.FirstName.ToLower().Contains(search)
|| u.LastName.ToLower().Contains(search)
|| u.EmailAddress.ToLower().Contains(search))
&& u.RoleID == (int)RoleEnum.Admin)
.Select(u => new { EmailAddress = u.EmailAddress })
.ToList();
}
The results are comparable with the inline one edging out ahead in speed. It's interesting that the extension-based one used a parameter for the roleID and the inline one did not. That's the only real difference I can see.
I really like the fluent-like style the Extension method provides, and how it encapsulates logic to prevent erroneous queries from being written (like forgetting to ToLower()
the string fields or something). Is there a good reason why this would be a Really Bad Idea? If not, I prefer the easy maintainability of the Extension methods over inline.
Db.Comments.By(currentUser).By(thread).OrderByDate()
. Personally I think it is really readable and well maintainable, but I still need to test that with others ;) \$\endgroup\$db.Users.By(RoleEnum.Admin).FilterBy(keyword).SelectEmails()
- but quite curious what others think. \$\endgroup\$