NHibernate Linq with subquery返回'当子查询没有引入EXISTS'时,只能在
本文关键字:EXISTS 查询 subquery with Linq 返回 NHibernate | 更新日期: 2023-09-27 18:17:25
我正试图得到以下查询工作:
var users = session.Query<PersonUser>()
.Select(u => new User()
{
Id = u.UserId,
FirstName = u.UserFirstName,
Surname = u.UserSurname,
ActiveRoles = u.Roles.Select(rr => new Role() { Id = rr.RoleId, DisplayName = rr.RoleName })
})
.ToList();
当我执行查询时,我得到以下内容:
NHibernate.Exceptions.GenericADOException occurred
Message=could not execute query
[ select personuser0_.USER_ID as col_0_0_, personuser0_.USER_FIRSTNAME as col_1_0_, personuser0_.USER_SURNAME as col_2_0_, (select personrole2_.ROLE_ID, personrole2_.ROLE_NAME from PERSON_ROLE_USER roles1_, PERSON_ROLE personrole2_ where personuser0_.USER_ID=roles1_.USER_ID and roles1_.ROLE_ID=personrole2_.ROLE_ID) as col_3_0_ from PERSON_USER personuser0_ ]
[SQL: select personuser0_.USER_ID as col_0_0_, personuser0_.USER_FIRSTNAME as col_1_0_, personuser0_.USER_SURNAME as col_2_0_, (select personrole2_.ROLE_ID, personrole2_.ROLE_NAME from PERSON_ROLE_USER roles1_, PERSON_ROLE personrole2_ where personuser0_.USER_ID=roles1_.USER_ID and roles1_.ROLE_ID=personrole2_.ROLE_ID) as col_3_0_ from PERSON_USER personuser0_]
Source=NHibernate
SqlString=select personuser0_.USER_ID as col_0_0_, personuser0_.USER_FIRSTNAME as col_1_0_, personuser0_.USER_SURNAME as col_2_0_, (select personrole2_.ROLE_ID, personrole2_.ROLE_NAME from PERSON_ROLE_USER roles1_, PERSON_ROLE personrole2_ where personuser0_.USER_ID=roles1_.USER_ID and roles1_.ROLE_ID=personrole2_.ROLE_ID) as col_3_0_ from PERSON_USER personuser0_
InnerException: System.Data.SqlClient.SqlException
Message=Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=116
Procedure=""
State=1
注:PersonUser
和PersonRole
为POCO数据库实体,User
和Role
为简单DTO。PersonUser.Roles
是List映射的hasmanymany .
我怎样才能让NH正确地项目到User
DTO,包括它的多对多关系到Role
DTO?
非常感谢你的帮助!
似乎sqlserver不接受查询,因为子查询返回多个列。你可以使用:
var users = session.Query<PersonUser>()
.Fetch(u => u.Roles).Eager
.AsEnumerable()
.Select(u => new User
{
Id = u.UserId,
FirstName = u.UserFirstName,
Surname = u.UserSurname,
ActiveRoles = u.Roles.Select(rr => new Role { Id = rr.RoleId, DisplayName = rr.RoleName }).ToList()
})
.ToList();