我正在编写一种方法让客户决定从表中选择哪些字段
这是我到目前为止所做的事情
public IList<User> List(int? roleId, int? sequence, string name,System.Linq.Expressions.Expression<Func<User, dynamic>> selector)
{
var query = context.Users.AsQueryable();
if (roleId.HasValue && roleId.Value > 0)
query = query.Where(x => x.RoleId == roleId);
if (sequence.HasValue && sequence.Value > 0)
query = query.Where(x => x.Sequence == sequence);
if (!string.IsNullOrEmpty(name))
query = query.Where(x => x.Name.Contains(name));
query = query.OrderBy(x => x.UserId);
var result = query.Select(selector).ToList();
var users = new List<User>();
User user = null;
foreach (var item in result)
{
user=new User();
user.UserId = item.id;
user.Name = item.name;
//user.Email = item.email;
//user.Sequence = item.sequence;
users.Add(user);
}
return users;
}
它编译错误说:item.id没有定义,但我可以看到项{id = 4,name =“sam”....}
答案 0 :(得分:1)
如果您希望能够选择客户端代码,要从数据库中检索哪些字段,那么为什么要将返回类型限制为User
?
让客户端代码选择它应该使用的返回类型:
public IList<T> List(int? roleId, int? sequence, string name,System.Linq.Expressions.Expression<Func<User, T>> selector)
{
// ...
query = query.OrderBy(x => x.UserId);
return query.Select(selector).ToList();
}
否则,我无法想象,您如何将从选择器返回的任何内容转换为User
个实例。