[英]Generic Entity Framework Read Method
I'm new to Entity Framework and would like some help with my Read Methods. 我是Entity Framework的新手,我的读取方法需要一些帮助。
I have this User
class and its UserDAO
with my methods. 我的方法有这个
User
类及其UserDAO
。
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: 您可以将where子句传递给函数:
See this answer: C# Linq where clause as a variable 看到这个答案: C#Linq where子句作为变量
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. 但是到那时,您基本上只是公开了一个IQueriable /重新发明了轮子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.