简体   繁体   中英

Generic Entity Framework Read Method

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM