c# - 如何使用 QueryOver 返回通用列表

标签 c# .net generics nhibernate queryover

我正在尝试使用 queryover 进行简单的选择并获取通用列表。

我只想从表中获取用户名电子邮件名字并忽略其余部分。

这是我的代码:

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;
}

错误:

值“x”不是“Model.Poco.Entities.Users”类型,不能在此通用集合中使用。\r\n参数名称:值

SQL 查询会是这样的

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;

错误:

值“System.Object[]”不是类型“Poco.Entities.Users”,不能在此通用集合中使用。\r\n参数名称:值

最佳答案

我们需要向每列添加 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>();

关于c# - 如何使用 QueryOver 返回通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30103604/

相关文章:

c# - 如何在 linq 中多次调用 .Where() 方法来表现得像 OR (||)

arrays - Ada -- 无约束对象队列数组导致 Storage_Error -- 如何解决?

ios - Swift:创建具有空字段的可变数组

java - 这是确定 Java 通配符 <?> referee 的运行时类型的最佳实践示例

c# - 在windows中用c#程序连接web服务器中的mysql数据库

c# - WinForms 菜单工具条获取状态

c# - 如何在 Linq 中的一行代码中对多个属性的列表进行排序

c# - 从 VS2017 附加到 docker 内正在运行的进程

c# - 如何仅导入类型而不导入实例?

.net - .net 中泛型的实际使用(框架中的泛型除外)