I'm trying to do a simple select with queryover and get a generic list.
我正在尝试使用queryover进行简单的选择并获得通用列表。
I want to get from the table only username
, email
and firstname
and omit the rest.
我想从表中只获取用户名,电子邮件和名字,并省略其余部分。
This is my code:
这是我的代码:
public IList<Users> GetAllByRole(string role)
{
var users= this.Session.QueryOver<Users>()
.where(f => f.role == role)
.select(f => f.username)
.select(f => f.email)
.select(f => f.firstname)
.list<Users>();
return users;
}
Error:
The value \"x\" is not of type \"Model.Poco.Entities.Users\" and cannot be used in this generic collection.\r\nParameter name: value
值“x”不是类型“Model.Poco.Entities.Users”,并且不能在此通用集合中使用。\ r \ nParameter name:value
SQL Query would be something like this
SQL Query就是这样的
SELECT [username]
,[email]
,[firstname]
FROM [MyDB].[dbo].[MyTable]
WHERE [role] = 'admin'
I also tried something like this
我也试过这样的事
IList<Users> users = this.Session.QueryOver<Users>()
.Where(p => p.role == role)
.SelectList(list => list
.Select(p => p.username)
.Select(p => p.email)
.Select(p => p.firstname)
)
.List<Users>();
return users;
Error:
The value \"System.Object[]\" is not of type \"Poco.Entities.Users\" and cannot be used in this generic collection.\r\nParameter name: value
值“System.Object [] \”的类型不是“Poco.Entities.Users”,并且不能在此通用集合中使用。\ r \ nParameter name:value
1 个解决方案
#1
We need to add 1) aliases to each column and use 2) transformer:
我们需要为每列添加1)别名并使用2)变换器:
// Users u - will serve as an alias source below
Users u = null;
IList<Users> users = this.Session.QueryOver<Users>()
.Where(f => f.role == role)
.SelectList(list => list // here we set the alias
.Select(p => p.username) .WithAlias(() => u.username)
.Select(p => p.email) .WithAlias(() => u.email)
.Select(p => p.firstname).WithAlias(() => u.firstname)
)
// here we Transform result with the aliases into Users
.TransformUsing(Transformers.AliasToBean<Users>())
.List<Users>();
#1
We need to add 1) aliases to each column and use 2) transformer:
我们需要为每列添加1)别名并使用2)变换器:
// Users u - will serve as an alias source below
Users u = null;
IList<Users> users = this.Session.QueryOver<Users>()
.Where(f => f.role == role)
.SelectList(list => list // here we set the alias
.Select(p => p.username) .WithAlias(() => u.username)
.Select(p => p.email) .WithAlias(() => u.email)
.Select(p => p.firstname).WithAlias(() => u.firstname)
)
// here we Transform result with the aliases into Users
.TransformUsing(Transformers.AliasToBean<Users>())
.List<Users>();