我正在尝试使用queryover进行简单的选择并获得通用列表。
我想仅从表中username
,email
和firstname
获取并省略其余内容。
这是我的代码:
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;
}
错误:
The value \"x\" is not of type \"Model.Poco.Entities.Users\" and cannot be used in this generic collection.\r\nParameter name: value
SQL Query就是这样的
SELECT [username]
,[email]
,[firstname]
FROM [MyDB].[dbo].[MyTable]
WHERE [role] = 'admin'
我也试过这样的事情
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;
错误:
The value \"System.Object[]\" is not of type \"Poco.Entities.Users\" and cannot be used in this generic collection.\r\nParameter name: value
答案 0 :(得分:5)
我们需要为每列添加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>();